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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;
template <class elemType>
void print(elemType[], int);
template <class elemType>
int partition(elemType[], int, int);
template <class elemType>
void swap(elemType[], int, int);
template <class elemType>
void recursiveQuick(elemType[], int, int);
template <class elemType>
void quickSort(elemType[], int);
int main()
{
int intList[100];
int num;
for(int i = 0; i < 100; i++)
{
num = (rand() + time(0)) % 10000;
intList[i] = num;
}
cout << "intList before sorting:" << endl;
print(intList, 100);
cout << endl << endl;
quickSort(intList, 100);
cout << "intList after quick sort: " << endl;
print(intList, 100);
cout << endl;
cin.get();
return 0;
}
template <class elemType>
void print(elemType list[], int length)
{
int count = 0;
for(int i = 0; i < length; i++)
{
cout << setw(5) << list[i];
count++;
if(count % 10 == 0)
cout << endl;
}
}
template <class elemType>
int partition(elemType list[], int first, int last)
{
elemType pivot;
int index, smallIndex;
swap(first, (first+last)/2);
pivot = list[first];
smallIndex = first;
for (index = first + 1; index <= last; index++)
if (list[index] < pivot)
{
smallIndex++;
swap(list, smallIndex, index);
}
swap(list, first, smallIndex);
return smallIndex;
}
template <class elemType>
void swap(elemType list[], int first, int second)
{
elemType temp;
temp = list[first];
list[first] = list[second];
list[second] = temp;
}
template <class elemType>
void recursiveQuick(elemType list[], int first, int last)
{
int pivotLocation;
if(first < last)
{
pivotLocation = partition(list, first, last);
recursiveQuick(list, first, pivotLocation - 1);
recursiveQuick(list, pivotLocation + 1, last);
}
}
template <class elemType>
void quickSort(elemType list[], int length)
{
recursiveQuick(list,0,length - 1);
}
|