-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick sort.cpp
More file actions
77 lines (57 loc) · 1.64 KB
/
Quick sort.cpp
File metadata and controls
77 lines (57 loc) · 1.64 KB
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
// Algorithm : Quick sort.
// Complexity : O(n log n) on everage case, O(n^2) on worst case.
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 10;
void quickSort(int arr[], int left, int right)
{
int i = left, j = right, pivot = arr[(left+right)/2];
// Partition.
while(i <= j) {
while(arr[i] < pivot) ++i;
while(arr[j] > pivot) --j;
if(i <= j) {
swap(arr[i], arr[j]);
++i, --j;
}
}
// Recursion.
if(left < j)
quickSort(arr, left, j);
if(i < right)
quickSort(arr, i, right);
}
int main()
{
int arr[MAXN];
for(int i = 0; i < MAXN; ++i)
arr[i] = rand() % 100;
puts("Before sorting:");
for(auto &x : arr) printf("%d ", x);
quickSort(arr, 0, MAXN-1);
puts("\nAfter sorting:");
for(auto &x : arr) printf("%d ", x);
return 0;
}
// -------------------- Alternatively (different partitioning method) --------------------
/*
int partition(int arr[], int left, int right)
{
int pivot = arr[right];
int i = left-1; // Index of smaller element.
for(int j = left; j < right; ++j)
if(arr[j] <= pivot) // If current element is smaller than or equal to pivot.
swap(arr[++i], arr[j]);
swap(arr[++i], arr[right]);
return i;
}
void quickSort(int arr[], int left, int right)
{
if(left < right) {
int index = partition(arr, left, right); // Partitioning index, arr[index] is now at the right place.
quickSort(arr, left, index-1);
quickSort(arr, index+1, right);
}
}
*/