voidswap(int tree[], int i, int j){ int tmp = tree[i]; tree[i] = tree[j]; tree[j] = tmp; }
//heapify 把一个最大的结点放到最前,然后对交换下来的点做heapify,以保持大根堆的结构(大根堆) //n是树上元素的个数,i表示从第i个结点开始heapify voidheapify(int tree[], int n, int i){ if(i >= n){ return; } int c1 = 2 * i + 1; int c2 = 2 * i + 2; int maxn = i; if(c1 < n && tree[c1] > tree[maxn]){ maxn = c1; } if(c2 < n && tree[c2] > tree[maxn]){ maxn = c2; } if(maxn != i){ swap(tree, maxn, i); heapify(tree, n, maxn); //对交换后的结点进行heapify } }
//建立堆 //假如是杂乱无章的数字,要从最后一个结点的parent结点开始,根据下标倒着进行堆化(3->2->1->0),就是图中的3 voidbuild_heap(int tree[], int n){ int last_node = n - 1; int parent = (last_node - 1) / 2; for(int i = parent; i >= 0; i--){ heapify(tree, n, i); } }
//堆排序 voidheap_sort(int tree[], int n){ build_heap(tree, n); for(int i = n - 1; i >= 0; i--){ swap(tree, i, 0); heapify(tree, i, 0); //每次从第0个结点开始做heapify } }
intmain() { int tree[] = {2, 5, 3, 1, 10, 4}; int n = 6; heap_sort(tree, n); for(int i = 0; i < n; i++){ cout << tree[i] <<endl; } return0; }
voidMerge(int arr[], int l, int m, int r){ int left_size = m - l; int right_size = r - m + 1; int left[left_size]; int right[right_size]; int i,j,k; //将排好序的左半部分放到左数组 for(i = l; i < m; i++){ left[i - l] = arr[i]; } //将排好序的左半部分放到左数组 for(i = m; i <= r; i++){ right[i - m] = arr[i]; } i = 0, j = 0, k = l; //Merge into the original array (实际用了双指针) while(i < left_size && j < right_size){ if(left[i] < right[j]){ arr[k++] = left[i]; i++; } else{ arr[k++] = right[j]; j++; } } //put the rest of elements into array while(i < left_size){ arr[k++] = left[i]; i++; }
voidmergeSort(int arr[], int l, int r){ if(l == r) return; else{ int m = (l + r) / 2; mergeSort(arr, l, m); mergeSort(arr, m+1, r); Merge(arr, l, m+1, r); } }
intmain() { int arr[] = {6,8,10,9,4,5,2,7}; int l = 0; // int m = 4; int r = 7; mergeSort(arr, l, r); for(int i = 0; i <= r; i++){ cout << arr[i] << endl; } return0; }