# Quick Sort in C++

Apr 7, 2021

A simple program quick sort in C++ program that I wrote while I am learning C++ programming.I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me at the following email address for further details.  If you want to advertise on my website kindly contact me also in my email address also. Thank you.

Program Listing

``````// quick_sort.cpp
// Prof. Jake R. Pomperada, MAED-IT, MIT
// Bacolod City, Negros Occidental Philippines

#include <iostream>
#include <cstdlib>

using namespace std;

void swap_numbers(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int Partition(int a[], int low, int high)
{
int pivot, index, i;
index = low;
pivot = high;

for(i=low; i < high; i++)
{
if(a[i] < a[pivot])
{
swap_numbers(&a[i], &a[index]);
index++;
}
}

swap_numbers(&a[pivot], &a[index]);

return index;
}

int RandomPivotPartition(int a[], int low, int high)
{
int pvt, n, temp;
n = rand();

pvt = low + n%(high-low+1);

swap_numbers(&a[high], &a[pvt]);

return Partition(a, low, high);
}

int QuickSort(int a[], int low, int high)
{
int pindex;
if(low < high)
{

pindex = RandomPivotPartition(a, low, high);

QuickSort(a, low, pindex-1);
QuickSort(a, pindex+1, high);
}
return 0;
}

int main()
{
int n=0, i=0;
cout <<"\n";
cout <<"\t\tQuick Sort in C++";
cout <<"\n\n";
cout<<"\tHow many items to be sorted? ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"\tEnter item no. "<<i+1<<": ";
cin>>arr[i];
}
cout <<"\n";
cout<<"\tUnSorted Items\n ";
cout <<"\n";
cout <<"\t";
for (i =0; i < n; i++) {
cout<<" ,"<<arr[i];
}
cout <<"\n";
QuickSort(arr, 0, n-1);
cout <<"\n\n";
cout<<"\tSorted Item \n";
cout <<"\n";
cout <<"\t";
for (i = 0; i < n; i++) {
cout<<" ,"<<arr[i];
}

cout <<"\n\n";
cout <<"\tEnd of Program";
cout <<"\n";
}
``````