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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

#include <iostream>
#include <time.h>
using namespace std;
clock_t total_elapsed_time = 0;
int partition(int *arr,int s,int l);
void qsort(int *arr,int s,int l)
{
int x=partition(arr,s,l);
if(s<x-1)
qsort(arr, s, x-1);
if(x+1<l)
qsort(arr,x+1,l);
}
int partition(int *arr,int s,int l)
{
clock_t call_begin = clock();
int pivot;
int pval;
int i,j,temp;
// ALGO 1 for partition function
i=s;j=s;
//i traverses over the array
//j resides over the element > arr[pivot]
pval=arr[l];
pivot=l;
while(i<l)
{
if(arr[i]<pval)
{
temp=arr[i];
arr[i]=arr[j];
arr[j++]=temp;
}
i++;
}
temp=arr[l];
arr[l]=arr[j];
arr[j]=temp;
total_elapsed_time+=(clock()-call_begin);
return j;
//ALGO 2 for partition function.
/*
i=s;j=l;
pivot=s;
pval=arr[pivot];
while(i<j)
{
if(pivot==i)
{
//make comparision with value at j
if(!(pval<arr[j]))
{
//swap
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
//pivot value has been shifted to arr[j]
pivot=j;
//now at ith position we have an element we just swapped with pivot, so move ahead at i
i++;
}
else
j--;
}
else
{
//this is for pivot==j
if(!(pval>arr[i]))
{
//swap
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
//pivot value has been shifted to arr[i]
pivot=i;
//now at jth position we have an element we just swapped with pivot, so move ahead(left) at j
j--;
}
else
i++;
}
}
total_elapsed_time+=(clock()-call_begin);
return i;
*/
}
int main()
{
int i,arr[100],n,t;
cin>>t;
while(t--)
{
total_elapsed_time=0;
cin>>n;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
qsort(arr,0,n-1);
for(i=0;i<n;i++)
cout<<arr[i]<<"\t";
cout<<"\n\nTOTAL TIME ELAPSED in PARTITION FUNCTION : "<<float(total_elapsed_time)/CLOCKS_PER_SEC;
}
return 0;
}

# Quick Sort

The basic outline of the Quick Sort function is to :
1) Find a pivot, place it on correct position(let index be p) in the array(index : s to l ). This will be achieved by a partition function.
2) Quick Sort the sub array (s to p-1).
3) Quick Sort the sub array (p+1 to l).
I have implemented the following code with 2 partition functions :
1st based on Wikipedia's Algo
2nd based on
comments powered by Disqus