Tuesday, 26 August 2014
Quick Sort
#include <iostream>
#include <string>
int Partition(int a[], int left, int right)
{
int pivot = a[left];
while (true)
{
while (a[left] < pivot)
left++;
while (a[right] > pivot)
right--;
if (left < right)
{
int temp = a[right];
a[right] = a[left];
a[left] = temp;
}
else
{
return right;
}
}
}
void QuickSort(int *arr, int left, int right)
{
if(left < right)
{
int pivot = Partition(arr, left, right);
//for(int i = 0; i < 9; i++)
// std::cout << arr[i] << " ";
// std::cout << "\n";
if(pivot > 1)
QuickSort(arr, left, pivot - 1);
if(pivot + 1 < right)
QuickSort(arr, pivot + 1, right);
}
}
void QuickSort(int *arr, int len)
{
QuickSort(arr, 0, len - 1);
}
void main()
{
int max;
std::cout << "\nProgram for Ascending order of Numeric Values using QUICK SORT";
std::cout << "\n\nEnter the total number of elements: ";
std::cin >> max;
int *numarray = new int[max];
for(int i = 0; i < max; i++)
{
std::cout << "\nEnter [" << i + 1 << "] element: ";
std::cin >> numarray[i];
}
std::cout << "Before Sorting : ";
for(int k = 0; k < max; k++)
std::cout << numarray[k] << " ";
std::cout << "\n";
QuickSort(numarray,max);
std::cout << "\n\nThe numbers in ascending orders are given below:\n\n";
for(int i = 0; i < max; i++)
{
std::cout << "Sorted [" << i + 1 << "] element: ";
std::cout << numarray[i];
std::cout << "\n";
}
delete [] numarray;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment