A-C/ex8_1.c

108 lines
1.8 KiB
C
Raw Normal View History

2022-06-10 00:55:54 +00:00
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define MAX 100
typedef int DataType;
typedef struct list{
DataType data[MAX];
int start;
int length;
}List;
/*
*/
void DirectSort(List *L){
int j;
for(int i = 2; i <= L->length; i++){
L->data[0] = L->data[i];
j = i-1;
while(L->data[0] < L->data[j]){
L->data[j+1] = L->data[j];
j = j-1;
}
L->data[j+1] = L->data[0];
}
}
/*
*/
void QuickSort(List *L, int first, int end){
int i = first, j = end, temp = L->data[i];
while(i < j){
while(i < j && temp <= L->data[j]){
j--;
}
L->data[i] = L->data[j];
while(i < j && L->data[i] <= temp){
i++;
}
L->data[j] = L->data[i];
}
L->data[i] = temp;
if(first < i-1){
QuickSort(L, first, i-1);
}
if(i+1 < end){
QuickSort(L, i+1, end);
}
}
/*
*/
void input(List *L){
printf("请输入线性表长度:");
scanf("%d", &L->length);
for(int i=L->start; i<L->start + L->length; i++){
printf("请输入第 %d 个元素:", i + 1 - L->start);
scanf("%d", &L->data[i]);
}
}
/*
*/
void output(List L){
printf("数组元素为:\n");
for(int i=L.start; i<L.start + L.length; i++){
printf("%d\t", L.data[i]);
}
printf("\n\n");
}
int main(){
List L;
L.length = 0;
int choice;
for(;;){
printf("\t\t1.直接插入排序\n");
printf("\t\t2.快速排序\n");
printf("\t\t0.退出\n");
printf("请选择:");
scanf("%d", &choice);
if(choice == 0) break;
switch (choice) {
case 1:
L.start = 1;
input(&L);
output(L);
DirectSort(&L);
output(L);
break;
case 2:
L.start = 0;
input(&L);
output(L);
QuickSort(&L, L.start, L.start + L.length - 1);
output(L);
break;
default:
break;
}
printf("请按任意键继续...");
getch();
system("cls");
}
printf("感谢使用,再见\n");
return 0;
}