forked from msdeep14/hackerranksolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort4.cpp
77 lines (73 loc) · 1.25 KB
/
quicksort4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//https://www.hackerrank.com/challenges/quicksort4
//mandeep singh @msdeep14
#include<iostream>
#include<stdlib.h>
using namespace std;
int qswap=0,iswap=0;
int insertion(int a[], int s)
{
int i, j;
int current;
for(i = 1; i< s; i++)
{
current = a[i];
for(j = i-1; j>=0; j--)
{
if(current < a[j])
{ a[j+1] = a[j];
iswap++;
}
else
break;
}
a[j+1] = current;
}
return iswap;
}
int partision(int a[],int start,int end,int iswap)
{
int temp;
int pivot=a[end];
int pindex=start;
for(int i=start;i<end;i++)
{
if(a[i]<=pivot)
{
temp=a[i];
a[i]=a[pindex];
a[pindex]=temp;
qswap++;
pindex++;
}
}
temp=a[pindex];
a[pindex]=a[end];
a[end]=temp;
qswap++;
iswap=iswap-qswap;
return pindex;
}
int quicksort(int a[],int start,int end,int iswap)
{
if(start<end)
{
int pindex=partision(a,start,end,iswap);
iswap=quicksort(a,start,pindex-1,iswap);
iswap=quicksort(a,pindex+1,end,iswap);
}
return iswap;
}
int main()
{
int i,j,n;
int arr[1000],brr[1000];
cin>>n;
for(i=0;i<n;i++)
cin>>arr[i];
for(i=0;i<n;i++)
brr[i]=arr[i];
iswap=insertion(arr,n);
iswap=quicksort(brr,0,n-1,iswap);
cout<<(iswap-qswap);
return 0;
}