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
| template<typename T> void insertionSort(T arr[], int n){
for( int i = 1 ; i < n ; i ++ ) {
for( int j = i ; j > 0 ; j-- ) if( arr[j] < arr[j-1] ) swap( arr[j] , arr[j-1] ); else break;
for( int j = i ; j > 0 && arr[j] < arr[j-1] ; j -- ) swap( arr[j] , arr[j-1] ); T e = arr[i]; int j; for (j = i; j > 0 && arr[j-1] > e; j--) arr[j] = arr[j-1]; arr[j] = e; }
return; } int main() {
int n = 20000; cout<<"Test for random array,size = "<<n<<", random range [0, "<<n<<"]"<<endl; int *arr1 = SortTestHelper::generateRandomArray(n,0,n); int *arr2 = SortTestHelper::copyIntArray(arr1, n);
SortTestHelper::testSort("Insertion Sort", insertionSort,arr1,n); SortTestHelper::testSort("Selection Sort", selectionSort,arr2,n);
delete[] arr1; delete[] arr2;
cout<<endl;
cout<<"Test for more ordered random array, size = "<<n<<", random range [0, 3]"<<endl; arr1 = SortTestHelper::generateRandomArray(n,0,3); arr2 = SortTestHelper::copyIntArray(arr1, n);
SortTestHelper::testSort("Insertion Sort", insertionSort,arr1,n); SortTestHelper::testSort("Selection Sort", selectionSort,arr2,n);
delete[] arr1; delete[] arr2;
cout<<endl;
int swapTimes = 100; cout<<"Test for nearly ordered array, size = "<<n<<", swap time = "<<swapTimes<<endl; arr1 = SortTestHelper::generateNearlyOrderedArray(n,swapTimes); arr2 = SortTestHelper::copyIntArray(arr1, n);
SortTestHelper::testSort("Insertion Sort", insertionSort,arr1,n); SortTestHelper::testSort("Selection Sort", selectionSort,arr2,n);
delete[] arr1; delete[] arr2;
return 0; }
|