-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathquick-sort.cpp
86 lines (66 loc) · 1.32 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
#include<iostream>
using namespace std;
#define MAX 20
void sort(int a[], int n);
void sort(int a[], int low, int up);
int partition(int a[], int low, int up);
int main()
{
int a[MAX], n;
cout << "Enter the number of elements : ";
cin >> n;
for( int i=0; i<n; i++ )
{
cout << "Enter element " << i+1 << ": " ;
cin >> a[i];
}
sort(a,n);
cout << "Sorted array is : ";
for( int i=0; i<n; i++ )
cout << a[i] << " ";
cout << "\n";
}
void sort(int a[], int n)
{
sort(a, 0, n-1);
}
void sort( int a[], int low, int up )
{
if( low >= up )
return;
int p = partition(a, low, up);
sort(a, low, p-1); /* Sort left sublist */
sort(a, p+1, up); /* Sort right sublist */
}
int partition(int a[], int low, int up)
{
int pivot = a[low];
int i = low+1; /* moves from left to right */
int j = up; /* moves from right to left */
int temp;
while( i <= j )
{
while( a[i] < pivot && i < up )
i++;
while( a[j] > pivot )
j--;
if( i < j ) /* swap a[i] and a[j] */
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
else /* found proper place for pivot */
break;
}
/* Proper place for pivot is j */
a[low] = a[j];
a[j] = pivot;
return j;
}