#include <stdio.h> void Input(int *a, int n) { int i; for (i = 0; i < n; ++i) { scanf("%d", &a[i]); } } void Output(int * a, int n) { int i; for (i = 0; i < n; ++i) { printf("%4d", a[i]); } printf("/n"); } void InsertSort(int * a, int n) { int i, j, temp; for (i = 1; i < n; ++i) { temp = a[i]; j = i - 1; while (temp < a[j] && j >= 0) { a[j + 1] = a[j]; --j; } a[j + 1] = temp; } } void Swap(int * a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } void BubbleSort(int * a, int n) { int i, j; int flag = 0; for (i = 0; i < n - 1; ++i) { flag = 0; for (j = 0; j < n - i - 1; ++j) { if (a[j] > a[j+1]) { flag = 1; Swap(a, j, j+1); } } if (flag == 0) break; } } void SelectSort(int * a, int n) { int i, j, index, min; for (i = 0; i < n; ++i) { min = a[i]; index = i; for (j = i; j < n; ++j) { if (a[j] < min) { index = j; min = a[j]; } } Swap(a, i, index); } } void Merge(int * a, int * auxiliary, int start, int mid, int end) { int i, j = mid + 1, k = start; for (i = start; i <= end; ++i) { auxiliary[i] = a[i]; } i = start; while (i <= mid && j <= end) { if (auxiliary[i] <= auxiliary[j]) { a[k++] = auxiliary[i++]; } else { a[k++] = auxiliary[j++]; } } if (i > mid) { for (i = j; i <= end; ++i) { a[k++] = auxiliary[i]; } } else { for (j = i; j <= mid; ++j) { a[k++] = auxiliary[j]; } } } void MSort(int * a, int * auxiliary, int start, int end) { if (start < end) { int mid = (start + end) / 2; MSort(a, auxiliary, start, mid); MSort(a, auxiliary, mid + 1, end); Merge(a, auxiliary, start, mid, end); } } void MergeSort(int *a, int n) { int * auxiliary = new int [n]; MSort(a, auxiliary, 0, n - 1); delete [] auxiliary; } int Partition(int *a, int start, int end) { int temp; temp = a[start]; while (start < end) { while (a[end] > temp && start < end) --end; a[start] = a[end]; while (a[start] <= temp && start < end) ++start; a[end] = a[start]; } a[start] = temp; return start; } void QuickSort(int *a, int start, int end) { if (start < end) { int pivot = Partition(a, start, end); QuickSort(a, start, pivot - 1); QuickSort(a, pivot + 1, end); } } // max heap void Heapify(int *a, int start, int end) { if (2 * start + 2 <= end) { if (a[2 * start + 1] > a[2 * start + 2]) { if (a[2 * start + 1] > a[start]) { Swap(a, start, 2 * start + 1); Heapify(a, 2 * start + 1, end); } } else { if (a[2 * start + 2] > a[start]) { Swap(a, start, 2 * start + 2); Heapify(a, 2 * start + 2, end); } } } else if (2 * start + 1<= end) { if (a[2 * start + 1] > a[start]) { Swap(a, start, 2 * start + 1); Heapify(a, 2 * start + 1, end); } } } void HeapSort(int * a, int n) { int i; for (i = n / 2; i >= 0; --i) { Heapify(a, i, n - 1); } for (i = 0; i < n - 1; ++i) { Swap(a, 0, n - 1 - i); Heapify(a, 0, n - 2 - i); } } int main() { int a[10]; Input(a, 10); Output(a, 10); // InsertSort(a, 10); // BubbleSort(a, 10); // SelectSort(a, 10); // MergeSort(a, 10); // int b[10]; // Merge(a, b, 0, 4, 9); // QuickSort(a, 0, 9); HeapSort(a, 10); Output(a, 10); return 0; }