Quick Sort Algorithm in C++

Quick sort algorithm in c++ for beginners. This program is to perform sorting as much as fast in c++ programming language in sorting algorithm. 

Sorting program is used to arrange the elements in ascending order to print the element in sorting program.  

Initialize the value of array size and enter the array elements in the sorting element in c++ programming language.

#include <iostream>
using namespace std;
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[50],n,i;
cout<<"Enter the number of array";
cin>>n;
cout<<"\nEnter array elements";
for(i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<"\nAfter sorting";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0; 
}
void quick_sort(int a[],int l,int u)
{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}
int partition(int a[],int l,int u)
{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do
{
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}

 

Output:

Enter the number of array

3

Enter array elements

23 45 67

After sorting 23 45 67

Do While to Execute Quick Sort Algorithm in C++

A variant of the while loop is the do/while loop. This loop will run the code block once before checking if the condition is true, and then it will loop again as long as the condition is true.

Return Statement in C++

The return statement returns control of the execution flow to the function that called it. 

There are no conditional statements required in this statement. A void function’s return statement may or may not return anything, but a non-void function’s return value must be returned.

Temp Variable in C++

Temp is a variable that is used to store temporary data that may be used later in the program execution. 

If you’re writing a program to swap two numbers, for example, temp could be used as a variable to temporarily store one of the numbers until the other is copied onto it. Using this program we can execute quick sort algorithm in c++.