#includeusing namespace std; int temp[10]; class SORT { public: SORT() { for (int i = 0; i < Arrzy_Size; i++) { cout << "请输入第"<> a[i]; } cout << "-----------------------" << endl; cout << "请选择排序算法" << endl; cout << "1.插入排序" << endl; cout << "2.冒泡排序" << endl; cout << "3.快速排序" << endl; cout << "4.简单选择排序" << endl; cout << "5.归并排序" << endl; cout << "6.堆排序" << endl; cin >> choice; switch (choice) { case 1:InsertSort(); Printf(); break; case 2:BubbleSort(); Printf(); break; case 3:quick_sort(0,Arrzy_Size-1); Printf(); break; case 4:Select_sort(); Printf(); break; case 5:Merge_sort(0,Arrzy_Size-1); Printf(); break; case 6:for (int i = (Arrzy_Size-1) / 2; i >=1; i--) down(i); Printf(); break; default:exit(0); } } private: void InsertSort()//插入排序 { int i, j, temp; for( i = 1;i temp = a[i];//记录当前i位置的值 for (j = i - 1; j >= 0 && a[j] > temp; j--)//j<0或a[j]<=temp时跳出循环 a[j + 1] = a[j]; a[j + 1] = temp; } } void BubbleSort()//冒泡排序 { for (int i = 0; i < Arrzy_Size; i++) { bool flag = false; for (int j = Arrzy_Size - 1; j > i; j--) { if (a[j - 1] > a[j]) { swap(a[j - 1], a[j]); flag = true; } } if (flag == false)return;//如果一趟冒泡排序没有发生交换,则说明已经有序,可以提前退出循环 } } void quick_sort(int l,int r )//快速排序 { if (l == r)return; int i = l - 1, j = r + 1; int x = a[l + r >> 1]; while (i do i++; while (a[i] < x); do j--; while (a[j] > x); if (i < j)swap(a[i], a[j]); } quick_sort(l, j); quick_sort(j + 1, r); } void Select_sort()//简单选择排序 { for (int i = 0; i < Arrzy_Size; i++) { int min = i; for (int j = i + 1; j < Arrzy_Size; j++) if (a[j] < a[min]) min = j; if (min != i)swap(a[i], a[min]); } } void Merge_sort(int l, int r)//归并排序 { if (l == r)return; int mid = l + r >> 1; Merge_sort(l, mid), Merge_sort(mid + 1, r); int i = l, j = mid+1,k = 0; while (i <= mid && j <= r) { if (a[i] <= a[j])temp[k++] = a[i++]; else temp[k++] = a[j++]; } while(i<=mid)temp[k++] = a[i++]; while(j<=r)temp[k++] = a[j++]; for (int i = l, j = 0; i <= r; i++, j++)a[i] = temp[j]; } void down(int u)//堆排序 { int t = u; if (2 * u <= Arrzy_Size && a[2 * u] < a[t]) t = 2 * u; if (2 * u + 1 <= Arrzy_Size && a[2 * u + 1] < a[t])t = 2 * u + 1; if (u != t) { swap(a[u], a[t]); down(t); } } void Printf() { cout << "排序结果:"; for (int i = 0; i < Arrzy_Size; i++) { cout << a[i] << " "; } cout << endl; } int choice; static const int Arrzy_Size = 10; int a[Arrzy_Size]; }; int main() { SORT test; system("pause"); return 0; }
对于堆排序代码需要特别处理,不能down(0)会出现不可预知的结果
所以堆的数据从a[1]开始存到a[9]只有9个数



