1. 编程实现如下功能:
(1)输入同样一组整型数据,作为待排序记录的关键字序列。
(2)在进行直接插入排序的同时,统计在排序过程中对关键字的比较次数和移动次数,并输出统计结果。
(3)在进行冒泡排序的同时,统计在排序过程中对关键字的比较次数和移动次数,并输出统计结果。
(4)在进行简单选择排序的同时,统计在排序过程中对关键字的比较次数和移动次数,并输出统计结果。
#include <iostream> #define MAXSIZE 21 using namespace std; typedef int KeyType; typedef struct { KeyType key; } RedType; typedef struct { RedType r[MAXSIZE]; int length = 0; //长度 } SqList; void InsertSort(SqList &L) //直接插入排序 { int j, i = j = 0, m = L.length; int compare, move = compare = 0; //比较次数和移动次数 for (i = 2; i <= m; i++) { if (L.r[i].key < L.r[i - 1].key) { L.r[0] = L.r[i]; L.r[i] = L.r[i - 1]; for (j = i - 2; L.r[0].key < L.r[j].key; j--) { L.r[j + 1] = L.r[j]; compare++; } L.r[j + 1] = L.r[0]; move++; compare++; } compare++; } cout << "\n直接插入排序比较次数:" << compare << " 移动次数:" << move << '\n'; } void BubbleSort(SqList &L) //冒泡排序 { int m = L.length, flag = 1; int compare, move = compare = 0; //比较次数和移动次数 RedType temp; while ((m > 0) && (flag == 1)) { flag = 0; for (int j = 1; j < m; j++) { if (L.r[j].key > L.r[j + 1].key) { flag = 1; temp = L.r[j]; L.r[j] = L.r[j + 1]; L.r[j + 1] = temp; move++; } compare++; } m--; } cout << "\n冒泡排序比较次数:" << compare << " 移动次数:" << move << '\n'; } void SelectSort(SqList &L) //简单选择排序 { int m = L.length, k; int compare, move = compare = 0; //比较次数和移动次数 RedType temp; for (int i = 1; i <= m; i++) { k = i; for (int j = i + 1; j <= m; j++) { if (L.r[j].key < L.r[k].key) { k = j; } compare++; } if (k != i) { temp = L.r[i]; L.r[i] = L.r[k]; L.r[k] = temp; move++; } } cout << "\n简单选择排序比较次数:" << compare << " 移动次数:" << move << '\n'; } void Show(SqList &L) //按顺序打印一组数据 { cout << "该组关键字序列为:\n"; for (int i = 1; i <= L.length; i++) { cout << L.r[i].key << '\t'; } cout << '\n'; } int main() { SqList L1; int num; cout << "请输入数据的个数(最大容量20):"; cin >> num; cout << "\n请分别输入数据:"; for (int i = 1; i <= num; i++) { cin >> L1.r[i].key; L1.length++; } SqList L2, L3 = L2 = L1; cout << "排序前:"; Show(L1); InsertSort(L1); cout << "直接插入排序后,"; Show(L1); BubbleSort(L2); cout << "冒泡排序后,"; Show(L2); SelectSort(L3); cout << "简单选择排序后,"; Show(L3); system("pause"); return 0; }