1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
// This program demonstrates the Quicksort algorithm.
#include <iostream>
#include <algorithm> //needed for swap() function
using namespace std;
// Function prototypes
template <class T>
T quickSort(T [], int, int);
template <class T>
T partition(T [], int, int);
int main()
{
// Array to be sorted.
const int SIZE = 10;
int array[SIZE] = {100, 35, 7, 21, 89, 10, 148, 983, 33, 29};
// Echo the array to be sorted.
for (int k = 0; k < SIZE; k++)
cout << array[k] << " ";
cout << endl;
// Sort the array using Quicksort.
quickSort(array, 0, SIZE-1);
// Print the sorted array.
for (int k = 0; k < SIZE; k++)
cout << array[k] << " ";
cout << endl;
return 0;
}
//************************************************
// quickSort() uses the QuickSort algorithm to *
// sort arr from arr[start] through arr[end]. *
//************************************************
T quickSort(T arr[], int start, int end)
{
if (start < end) //test for base case start == end
{
// Partition the array and get the pivot point.
int p = partition(arr, start, end);
// Sort the portion before the pivot point.
quickSort(arr, start, p - 1);
// Sort the portion after the pivot point.
quickSort(arr, p + 1, end);
}
return; //base case
}
//***********************************************************
// partition() rearranges the entries in the array arr from *
// start to end so all values greater than or equal to the *
// pivot are on the right of the pivot and all values less *
// than are on the left of the pivot. *
//***********************************************************
T partition(T arr[], int start, int end)
{
// The pivot element is taken to be the element at
// the start of the subrange to be partitioned.
T pivotValue = arr[start];
T pivotPosition = start;
// Rearrange the rest of the array elements to
// partition the subrange from start to end.
for (int pos = start + 1; pos <= end; pos++)
{
if (arr[pos] < pivotValue)
{
// arr[pos] is the "current" item.
// Swap the current item with the item to the
// right of the pivot element.
swap(arr[pivotPosition + 1], arr[pos]);
// Swap the current item with the pivot element.
swap(arr[pivotPosition], arr[pivotPosition + 1]);
// Adjust the pivot position so it stays with the
// pivot element.
pivotPosition ++;
}
}
return pivotPosition;
}
|