Skip to content

Instantly share code, notes, and snippets.

@piyush01123
Last active February 17, 2023 19:01
Show Gist options
  • Save piyush01123/169b8b22dd7dc862fa37f29fa95fda0f to your computer and use it in GitHub Desktop.
Save piyush01123/169b8b22dd7dc862fa37f29fa95fda0f to your computer and use it in GitHub Desktop.
QuickSort implementation
#include <bits/stdc++.h>
using namespace std;
int randGen (int i) {srand(time(0)); return rand()%i;}
int ctr = 0;
int partition(int A[], int lo, int hi)
{
int pivot = A[hi];
int i = lo-1;
for (int j=lo; j<=hi; j++)
{
if (A[j]>pivot) continue;
i ++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
return i;
}
void quickSort(int A[], int lo, int hi)
{
ctr++;
if (lo>=hi) return;
int pi = partition(A, lo, hi);
quickSort(A, lo, pi-1);
quickSort(A, pi+1, hi);
return;
}
int main()
{
int A[] = {1,2,3,4,5,6,7};
int n = sizeof(A)/sizeof(int);
random_shuffle(A, A+n, randGen);
cout << " Input:";
for (int i=0; i<n; i++)cout<<A[i]<<','; cout<<endl;
cout << " Output:";
quickSort(A, 0, n-1);
for (int i=0; i<n; i++)cout<<A[i]<<','; cout<<endl;
cout << "NumCalls:"<< ctr << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment