Implementation
#include <iostream>
using namespace std;
int partition(int a[], int l, int h)
{
int pivot = a[l]; // pivot element
int i = l;
int j = h;
while (i < j)
{
while (a[i] <= pivot)
{
i++;
}
while (a[j] > pivot)
{
j--;
}
if (i < j)
{
swap(a[i], a[j]);
}
}
swap(a[l], a[j]);
return j;
}
/* function to implement quick sort */
void quick(int a[], int l, int h)
{
if (l < h)
{
int p = partition(a, l, h); // p is the partitioning index
quick(a, l, p - 1);
quick(a, p + 1, h);
}
}
// Driver code
int main()
{
// int a[] = {23, 8, 28, 13, 18, 26};
int a[] = {9,4,3,11,15,20,2,24,30,1,35};
int n = 10;
quick(a, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
Output
Sorted array: 1 2 3 4 9 11 15 20 24 30
0 Comments