标签:while heap 快速 tmp 堆排 class color oid stream
1 void quick_sort(int q[], int l, int r) 2 { 3 if (l >= r) return; 4 5 int i = l - 1, j = r + 1, x = q[l + r >> 1]; 6 while (i < j) 7 { 8 do i ++ ; while (q[i] < x); 9 do j -- ; while (q[j] > x); 10 if (i < j) swap(q[i], q[j]); 11 } 12 quick_sort(q, l, j), quick_sort(q, j + 1, r); 13 }
1 void merge_sort(int q[], int l, int r) 2 { 3 if (l >= r) return; 4 5 int mid = l + r >> 1; 6 merge_sort(q, l, mid); 7 merge_sort(q, mid + 1, r); 8 9 int k = 0, i = l, j = mid + 1; 10 while (i <= mid && j <= r) 11 if (q[i] < q[j]) tmp[k ++ ] = q[i ++ ]; 12 else tmp[k ++ ] = q[j ++ ]; 13 14 while (i <= mid) tmp[k ++ ] = q[i ++ ]; 15 while (j <= r) tmp[k ++ ] = q[j ++ ]; 16 17 for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j]; 18 }
1 #include<iostream> 2 using namespace std; 3 4 void heapInsert(int arr[], int index)//添加一个元素,形成大根堆 5 { 6 while (arr[index] > arr[(index - 1) / 2]) 7 { 8 swap(arr[index], arr[(index - 1) / 2]); 9 index = (index - 1) / 2; 10 } 11 } 12 13 void heapify(int arr[], int index, int heapSize)//改变一个元素,形成大根堆 14 { 15 int left = index * 2 + 1; 16 while (left < heapSize) 17 { 18 int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left; 19 20 largest = arr[largest] > arr[index] ? largest : index; 21 if (largest == index) 22 { 23 break; 24 } 25 else 26 { 27 swap(arr[largest], arr[index]); 28 index = largest; 29 left = index * 2 + 1; 30 } 31 } 32 } 33 34 void heapSort(int arr[],int n) 35 { 36 if (n < 2) 37 { 38 return; 39 } 40 41 //1、整体变成大根堆 42 for (int i = 0; i < n; i++) 43 { 44 heapInsert(arr, i); 45 } 46 47 //2、最后一个位置与堆顶位置作交换 48 swap( arr[0], arr[--n]); 49 50 while (n > 0) 51 { 52 heapify(arr, 0, n);//3、重新整理成大根堆 53 swap( arr[0], arr[--n]);//4、最后一个位置与堆顶位置作交换 54 } 55 } 56 57 58 int main() 59 { 60 int num[] = {9,5,4,2,3,1,8}; 61 heapSort(num,7); 62 for(int i = 0;i < 7;++i) 63 { 64 cout << num[i] << endl; 65 } 66 return 0; 67 }
标签:while heap 快速 tmp 堆排 class color oid stream
原文地址:https://www.cnblogs.com/yuhong1103/p/12872777.html