1. define some basic functions
1 #include <iostream> 2 3 using namespace std; 4 5 void _swap(int& a, int& b) 6 { 7 int tmp = b; 8 b = a; 9 a = tmp; 10 } 11 12 int main() 13 { 14 int a[] = {1, 5, 3, 6, 9, 4, 2, . 8 , . 7 }; 15 int n-= the sizeof (A) / the sizeof (A [ 0 ]); 16 . 17 bubbleSort (A, n-); // specific algorithm see later section 18 is QUICKSORT (A, n-); . 19 insetSort ( A, n-); 20 is shellSort (A, n-); 21 is SelectSort (A, n-); 22 is heapSort (A, n-); 23 is mergesort (A, n-); 24 25 for ( int I = 0 ; I <n-; ++ I ) 26 is { 27 COUT << A [I] << " "; 28 } 29 cout << endl; 30 31 32 while(1); 33 34 return 0; 35 }
2. Bubble Sort
1 void bubbleSort(int *arr, int n) 2 { 3 for(int i = 0; i < n; i++) 4 { 5 for(int j = 0; j< n - i - 1; j++) 6 { 7 if(arr[j] > arr[j+1]) 8 { 9 _swap(arr[j], arr[j+1]); 10 } 11 } 12 } 13 }
3. Quick Sort
. 1 int _part ( int * ARR, int Start, int End) 2 { . 3 int MID = Start; . 4 the while (Start < End) . 5 { . 6 the while (Start <End && ARR [End]> = ARR [MID]) / / where arr [end]> = arr [ mid] or arr [end]> same arr [mid] effect, no effect . 7 { . 8 - End; . 9 } 10 . 11 the while (Start <End && ARR [Start] <= ARR [MID]) // here arr [start] <= arr [ mid] or arr [start] <arr [mid ] the same effect, no effect 12 { 13 ++start; 14 } 15 16 if(start < end) 17 { 18 _swap(arr[start], arr[end]); 19 } 20 } 21 22 _swap(arr[start], arr[mid]); 23 24 return start; 25 } 26 27 void _quickSort(int *arr, int start, int end) 28 { 29 if(start >= end) 30 { 31 return; 32 } 33 34 int mid = _part(arr, start, end); 35 _quickSort(arr, start, mid - 1); 36 _quickSort(arr, mid + 1, end); 37 } 38 39 void quickSort(int *arr, int n) 40 { 41 _quickSort(arr, 0, n-1); 42 }
Quick sort algorithm is the most widely used one algorithm, sort algorithm standard STL library to use the quick-sort algorithm, however, is not simply the use of this kind of quick sort algorithm, but use a variety of hybrid algorithm algorithms to quickly sort algorithm-based, subsequent chapters will be slowly introduced.