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 105 106 107
| #ifndef QUICKSORT_H_ #define QUICKSORT_H_
#include <iostream> #include <vector> using namespace std;
#define ElementType int
void Insertion_Sort(ElementType* PtrA, long int Number){ ElementType temp; long int i; for(long int P = 1; P < Number; P++){ temp = *(PtrA + P); for(i = P; i > 0 && *(PtrA + i - 1) > temp; i--){ *(PtrA + i) = *(PtrA + i - 1); } *(PtrA + i) = temp; } }
void Swap(ElementType *A, ElementType *B){ ElementType temp; temp = *A; *A = *B; *B = temp; }
ElementType Median3(vector<ElementType> &A, long int Left, long int Right){ long int Center = (Left + Right)/ 2 ; if(A[Left] > A[Center]){ Swap(&A[Left], &A[Center]); } if(A[Left] > A[Right]){ Swap(&A[Left], &A[Right]); } if(A[Center] > A[Right]){ Swap(&A[Center], &A[Right]); } Swap(&A[Center], &A[Right-1]); return A[Right-1]; }
#define Cutoff 5 void Quicksort(vector<ElementType> &A, long int Left, long int Right){ ElementType pivot; long int i, j;
if((Right - Left)>= Cutoff){ pivot = Median3(A, Left, Right); i = Left ; j = Right - 1 ; for(; ;){ while(A[++i] < pivot){} while(A[--j] > pivot){} if(i < j){ Swap(&A[i], &A[j]); } else { break; } } Swap(&A[i], &A[Right-1]); Quicksort(A, Left, i-1); Quicksort(A, i+1, Right); } else { Insertion_Sort( &A[Left], Right-Left+1); } }
void Quick_Sort(vector<ElementType> &A, long int Number){ Quicksort(A, 0, Number-1); }
void Print_Array(vector<ElementType> &A, long int Number){ int NumberOfPreRows = 10; for(long int i=0; i<Number; i++){ cout << " " << A[i]; if(i%NumberOfPreRows == (NumberOfPreRows-1)){ cout << endl; } } } #endif
|