Easy Program For Quick Sort CPP
The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:- Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.
- Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
- Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
PROGRAM:
#include<iostream>
using namespace std;
const int SIZE=10;
void q_sort(int arr[], int l, int r)
{
int pivot = arr[l]; // your pivot is element/data of l
int left = l;
int right = r;
while(l<r)
{
while(arr[r] >= pivot && l<r )
r--;
if(l != r)
{
arr[l] = arr[r];
l++;
}
while(arr[l] <= pivot && l<r )
l++;
if(l != r)
{
arr[r] = arr[l];
r--;
}
}
arr[l]=pivot;
pivot=l; // pivot is not index of pivot element
if(left < pivot)
q_sort(arr, left, pivot-1);
if(pivot < right)
q_sort(arr, pivot+1, right);
}
void quick_sort(int arr[])
{
q_sort(arr, 0, SIZE-1);
}
int main()
{
int arr[SIZE];
cout<<"Enter 10 elements\n";
for(int i=0; i<10; i++)
{
cin>>arr[i];
}
quick_sort(arr);
cout<<"After sorting\n";
for(int i=0; i<10; i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
OUTPUT:
Enter 10 elements
63
51
499
01
45
1
63
97
2
4
After sorting
1
1
2
4
45
51
63
63
97
499
C++ Quick Sort Most Simple Program |
#COFPROG
Sign up here with your email
ConversionConversion EmoticonEmoticon