109 lines
1.9 KiB
C
109 lines
1.9 KiB
C
|
#include<stdio.h>
|
||
|
#include<stdlib.h>
|
||
|
#include<conio.h>
|
||
|
#define MAX 100
|
||
|
typedef int DataType;
|
||
|
typedef struct list{
|
||
|
int 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;
|
||
|
}
|
||
|
|