Skip to content

Instantly share code, notes, and snippets.

@greatsharma
Last active April 29, 2019 09:56
Show Gist options
  • Save greatsharma/d5a9f8a8f6c5f6135c344662c17faf03 to your computer and use it in GitHub Desktop.
Save greatsharma/d5a9f8a8f6c5f6135c344662c17faf03 to your computer and use it in GitHub Desktop.
A simple c++ program to sort an array using Quick sort algorithm.
/*
Name: Quick Sort
Author: Gaurav Sharma
Date: 27-04-19 18:01
Description: A simple c++ program to sort an array using Quick sort algorithm.
*/
#include <iostream>
#include <conio.h>
#include <time.h>
#define NO_RUNS 100
int count = 0;
using namespace std;
void circularShift(int *Arr, const int &start, const int &end)
{
int temp = Arr[end];
for (int i = end - 1; i >= start; --i)
{
Arr[i + 1] = Arr[i];
}
Arr[start] = temp;
}
int partition(int *Arr, const int &start, const int &end)
{
int piv = start; // select first element as pivot.
int var = start + 1;
for (int i = start; i < end; ++i)
{
++count;
if (Arr[piv] > Arr[var])
{
circularShift(Arr, piv++, var++);
}
else
++var;
}
return piv;
}
void quickSort(int *Arr, int start, int end)
{
if (start < end)
{
int piv_pos = partition(Arr, start, end);
quickSort(Arr, start, piv_pos - 1);
quickSort(Arr, piv_pos + 1, end);
}
}
int main()
{
srand(time(0));
int *compr_array = new int[NO_RUNS];
cout << "\nquick sort: \n";
for (int k = 0; k < NO_RUNS; k++)
{
cout << "\n\nRUN " << k + 1;
int size = 5 + (rand() % (15 - (5) + 1));
cout << "\n\nsize : " << size;
int *arr = new int[size];
cout << "\n\nInitial array : ";
for (int i = 0; i < size; i++)
{
arr[i] = -100 + (rand() % (100 - (-100) + 1));
cout << " " << arr[i];
}
quickSort(arr, 0, size - 1);
int no_comp = count;
compr_array[k] = no_comp;
cout << "\n\ntotal no of comparisons : " << no_comp;
cout << "\n\nSorted array : \n";
for (int i = 0; i < size; i++)
{
cout << "\n"
<< arr[i];
}
}
getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment