Skip to content

Instantly share code, notes, and snippets.

@rahuladream
Created October 9, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahuladream/701998edfa6e1cdfa0def4011362261c to your computer and use it in GitHub Desktop.
Save rahuladream/701998edfa6e1cdfa0def4011362261c to your computer and use it in GitHub Desktop.
Quick Sort
#include <bits/stdc++.h>
using namespace std;
void quicksort(int[],int,int);
int partition(int[],int,int);
// Input and Main Function
int main()
{
int a[30],p,n,r;
cout<<"enter the number of element";
cin>>n;
cout<<"enter the element :";
for(int i=0; i<n; i++)
{
cin>>a[i];
}
// Call of initial function
quicksort(a,0,n-1);
cout<<"\n Array after sorting";
for(int i=0; i<n; i++)
{
cout << a[i] << " ";
}
return 0;
}
void quicksort(int a[], int p, int r)
{
if(p<r)
{
//Partition of element
int q;
q=partition(a, p, r);
quicksort(a,p,q);
quicksort(a,q+1,r);
}
}
int partition(int a[], int p, int r)
{
int i,j,pivot,temp;
pivot=a[p];
i=p;
j=r;
while(1)
{
/*
i -> will keep on traversing the list,
j -> we will keep on traverse the list from back
*/
while(a[i] < pivot && a[i] != pivot)
i++;
while(a[j] > pivot && a[j] != pivot)
j--;
if(i<j)
{
/*
Store the sorted value in file and return to temp
*/
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
return j;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment