// Program to implement quick sort in c++
#include<iostream>
using namespace std;
#define Max 30
void Quick_Sort(int data[],int first,int last);
int main()
{
int data[Max],number_of_elements,index;
cout<<"\\nEnter your number of elements to be sorted : ";
cin>>number_of_elements;
// accepting string as space seperated inputs
cout<<"\\nEnter the elements:";
for(index = 0;index < number_of_elements ;index++)
{
cin>>data[index];
}
// calling the quick sort function with first position as 0 and last position as list size -1
Quick_Sort(data, 0, number_of_elements-1);
// printing the sorted list
cout<<"\\nElements after sorting are :";
for(index = 0; index < number_of_elements; index++)
{
cout<<data[index] <<" ";
}
}
// recursive function to implement quick sort
void Quick_Sort(int data[],int first,int last)
{
int pivot, left_mark, right_mark, temp;
// checking if the array has more than one number
if(first < last)
{
pivot = first;
left_mark = first;
right_mark = last;
// loop while left marker is less than right marker
while(left_mark < right_mark)
{
// while the data at the left mark is less than pivot keep incrementing the left_mark
while(data[left_mark] <= data[pivot] && left_mark < right_mark)
left_mark++;
// while the data at the right mark is greater than pivot keep decrementing the right_mark
while(data[right_mark] >= data[pivot] && left_mark <= right_mark)
right_mark--;
// swap the elements if right mark is greater than left mark
if(right_mark > left_mark)
{
temp = data[right_mark];
data[right_mark] = data[left_mark];
data[left_mark] = temp;
}
// finally swap the pivot and the right mark element
temp = data[pivot];
data[pivot] = data[right_mark];
data[pivot] = temp;
}
// make recursive calls to the function
Quick_Sort(data, first, right_mark-1);
Quick_Sort(data, right_mark+1, last);
}
}