将这段代码改为键盘输入需要排序的数字#include <iostream> using namespace std; #define MAXSIZE 100 typedef struct { int key; char* otherinfo; } ElemType; typedef struct { ElemType* r; int length; } SqList; void BubbleSort(SqList* L) { int m = L->length - 1; int flag = 1; ElemType t; 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; t = L->r[j]; L->r[j] = L->r[j + 1]; L->r[j + 1] = t; } } m--; } } void InsertSort(SqList* L) { for (int i = 2; i <= L->length; i++) { if (L->r[i].key < L->r[i - 1].key) { L->r[0] = L->r[i]; int j; for (j = i - 1; L->r[0].key < L->r[j].key; j--) { L->r[j + 1] = L->r[j]; } L->r[j + 1] = L->r[0]; } } } int main() { int j; SqList L; L.r = new ElemType[MAXSIZE + 1]; L.length = 0; // 初始化 SqList 的 r 数组 for (int i = 1; i <= MAXSIZE; i++) { L.r[i].key = rand(); } L.length = MAXSIZE; printf("排序\n"); printf("***************************************************\n"); printf(" 1-----冒泡排序 \n"); printf(" 2-----直接插入 *\n"); printf
时间: 2023-08-06 14:09:38 浏览: 95
可以将代码改为以下形式,使用循环读取键盘输入的数字,并将其存储到数组中,然后再进行排序:
```cpp
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct {
int key;
char* otherinfo;
} ElemType;
typedef struct {
ElemType* r;
int length;
} SqList;
void BubbleSort(SqList* L) {
int m = L->length - 1;
int flag = 1;
ElemType t;
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;
t = L->r[j];
L->r[j] = L->r[j + 1];
L->r[j + 1] = t;
}
}
m--;
}
}
void InsertSort(SqList* L) {
for (int i = 2; i <= L->length; i++) {
if (L->r[i].key < L->r[i - 1].key) {
L->r[0] = L->r[i];
int j;
for (j = i - 1; L->r[0].key < L->r[j].key; j--) {
L->r[j + 1] = L->r[j];
}
L->r[j + 1] = L->r[0];
}
}
}
int main() {
int n, j;
SqList L;
L.r = new ElemType[MAXSIZE + 1];
L.length = 0; // 初始化 SqList 的 r 数组
printf("请输入需要排序的数字个数(不超过100个):");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
printf("请输入第%d个数字:", i);
scanf("%d", &(L.r[i].key));
}
L.length = n;
printf("排序\n");
printf("***************************************************\n");
printf(" 1-----冒泡排序 \n");
printf(" 2-----直接插入 *\n");
printf("***************************************************\n");
printf("请选择排序算法:");
scanf("%d", &j);
switch (j) {
case 1:
BubbleSort(&L);
break;
case 2:
InsertSort(&L);
break;
default:
printf("输入有误!\n");
break;
}
printf("排序结果:\n");
for (int i = 1; i <= L.length; i++) {
printf("%d ", L.r[i].key);
}
printf("\n");
return 0;
}
```
阅读全文