1
+ #include < iostream>
2
+ using namespace std ;
3
+ // Swap two elements - Utility function
4
+ void swap (int * a, int * b)
5
+ {
6
+ int t = *a;
7
+ *a = *b;
8
+ *b = t;
9
+ }
10
+
11
+ // partition the array using last element as pivot
12
+ int partition (int arr[], int low, int high)
13
+ {
14
+ int pivot = arr[high]; // pivot
15
+ int i = (low - 1 );
16
+
17
+ for (int j = low; j <= high- 1 ; j++)
18
+ {
19
+ // if current element is smaller than pivot, increment the low element
20
+ // swap elements at i and j
21
+ if (arr[j] <= pivot)
22
+ {
23
+ i++; // increment index of smaller element
24
+ swap (&arr[i], &arr[j]);
25
+ }
26
+ }
27
+ swap (&arr[i + 1 ], &arr[high]);
28
+ return (i + 1 );
29
+ }
30
+
31
+ // quicksort algorithm
32
+ void quickSort (int arr[], int low, int high)
33
+ {
34
+ if (low < high)
35
+ {
36
+ // partition the array
37
+ int pivot = partition (arr, low, high);
38
+
39
+ // sort the sub arrays independently
40
+ quickSort (arr, low, pivot - 1 );
41
+ quickSort (arr, pivot + 1 , high);
42
+ }
43
+ }
44
+
45
+ void displayArray (int arr[], int size)
46
+ {
47
+ int i;
48
+ for (i=0 ; i < size; i++)
49
+ cout<<arr[i]<<" \t " ;
50
+
51
+ }
52
+
53
+ int main ()
54
+ {
55
+ int arr[] = {12 ,23 ,3 ,43 ,51 ,35 ,19 ,45 };
56
+ int n = sizeof (arr)/sizeof (arr[0 ]);
57
+ cout<<" Input array" <<endl;
58
+ displayArray (arr,n);
59
+ cout<<endl;
60
+ quickSort (arr, 0 , n-1 );
61
+ cout<<" Array sorted with quick sort" <<endl;
62
+ displayArray (arr,n);
63
+ return 0 ;
64
+ }
0 commit comments