排序算法——QuickSort、MergeSort、HeapSort(C++实现)
快速排序QuickSort
template <class Item> void quickSort (Item a[], int l, int r) { if (r<=l) return; int i = partition(a, l, r); quickSort(a, l, i-1); quickSort(a, i+1, r); } template <class Item> int partition (Item a[], int l, int r) { int i = l -1, j = r; Item v = a[r]; for ( ; ; ) { while (a[++i] < v); while (a[--j] > v) if (j == i) break; if (i >= j) break; exch (a[i], a[j]); } exch (a[i], a[r]); return i; }
快速排序的思想可以用来找出数组中第k大的数
template <class Item> Item select (Item a[], int l, int r, int k) { if (r <= l) return a[l]; int i = partition(a, l, r); if (i > k) select(a, l, i-1, k); if (i < k) select(a, i+1, r, k); }
归并排序MergeSort
数组实现
template <class Item> void merge(Item a[], int l, int m, int r) { int i, j; static Item aux[maxN]; for (i = m; i>=l; i--) aux[i] = a[i]; for (j = m; j<r; j++) aux[r+m-j] = a[j+1]; for (int k = l; k<=r; k++) { if (aux[j] < aux[i]) a[k] = aux[j--]; else a[k] = aux[i++]; } } template <class Item> void mergeSort (Item a[], int l, int r) { if (r <= l) return; int m = (r+l) / 2; mergeSort(a, l, m); mergeSort(a, m+1, r); merge(a, l, m, r); }
链表实现
link merge (link a, link b) { node dummy(0); link head = &dummy, c = head; while ((a!=0) && (b!=0)) { if (a->item < b->item) { c->next = a; c = a; a = a->next; } else { c->next = b; c = b; b = b->next; } } c->next = (a==0) ? b : a; return head->next; } link mergeSort (link c) { if (c==0 || c->next==0) return c; link a = c, b = c->next; while ((b!=0) && (b->next!=0)) { c = c->next; b = b->next->next; } return merge (mergeSort(a), mergeSort(b)); }
堆排序HeapSort
template <class Item> void fixDown (Item a[], int k, int n) { while (2*k+1 < n) { int child = 2*k + 1; if ((child+1<n) && (a[child]<a[child+1]) child++; if (a[k] < a[child]) { exch(a[k], a[child]); k = child; } else return; } template <class Item> void heapSort (Item a[], int n) { int k; // 建堆 for (k = n/2; k >= 0; k--) fixDown(a, k, n); //排序 while (n-1>0) { exch (a[0], a[n-1]); fixDown(a, k, --n); } }