-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathquick_sort.cpp
69 lines (59 loc) · 1.16 KB
/
quick_sort.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
#include <bits/stdc++.h>
using namespace std;
int arr[10];
int partition(int low, int high);
void QuickSort(int low, int high)
{
if(low < high)
{
int j = partition(low, high);
QuickSort(low, j);
QuickSort(j+1, high);
}
}
int main()
{
int i, j;
srand(time(0));
cout<<"The given array is :"<<endl;
for (i = 0; i < 10; i++)
{
arr[i] = rand()%100;
cout<<arr[i]<<"\t";
}
int low = 0, high = 10;
arr[high] = 999; // A high value which can't occur in the array acts as terminator
QuickSort(low, high);
cout<<"\nThe sorted array is :"<<endl;
for (i = 0; i < 10; i++)
{
cout<<arr[i]<<"\t";
}
return 0;
}
int partition(int low, int high)
{
int pivot = arr[low];
int i=low, j = high;
while(i<j)
{
do
{
i++;
} while (arr[i]<=pivot);
do
{
j--;
} while (arr[j]>pivot);
if(i<j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[low];
arr[low] = arr[j];
arr[j] = temp;
return j;
}