#include<stdio.h> #include<stdlib.h>#include <windows.h> #define MAX 20 typedefstruct {
intelem[MAX];
intlength;
}Seqlist;
SeqlistInitlist() {
SeqlistL;L.length=0;
returnL;
}
SeqlistCreate(SeqlistL) {
intx;
scanf_s("%d", &x);
while (x!=-1)
{
L.elem[L.length] =x;
L.length++;
scanf_s("%d", &x);
}
printf("创建成功\n");
returnL;
}
voidInsertSort(SeqlistL){
inti,j,temp;
for(i=1;i<L.length;i++)if((L.elem[i]<(L.elem[i-1]))) {
temp=(L.elem[i]);
(L.elem[i]=(L.elem[i-1]));
for(j=i-1;(L.elem[j])>temp&&j>=0;j--) (L.elem[j+1]=(L.elem[j]));
(L.elem[j+1])=temp;
showout(L);
printf("\n");
}
}
voidSelectSort(SeqlistL){
for(inti=1;i<=L.length;i++){intmin=i;
for(intj=i+1;j<=L.length;j++){
if(L.elem[j]<L.elem[min]){
min=j;
}
}
if(min!=i){intt=L.elem[i];
L.elem[i]=L.elem[min];
L.elem[min]=t;
showout(L);
printf("\n");
}
}
}
voidmaopao(SeqlistL) {
inti, j, t;
for (i=0; i<L.length-1; i++)for (j=0; j<L.length-1-i; j++)
{
if (L.elem[j]>L.elem[j+1])
{
t=L.elem[j]; L.elem[j] =L.elem[j+1]; L.elem[j+1] =t;
}
showout(L);
printf("\n");
}
}
voidQuickSort(SeqlistL, intlow, inthigh){
if (low<high){
inti=low;intj=high;intk=L.elem[low];
while (i<j){
while(i<j&&L.elem[j] >=k) j--;
if(i<j) L.elem[i++] =L.elem[j];
while(i<j&&L.elem[i] <k) i++;
if(i<j) L.elem[j--] =L.elem[i];
showout(L);
printf("\n");
}
L.elem[i] =k;
QuickSort(L, low, i-1);
QuickSort(L, i+1, high);
showout(L);
printf("\n");
}
}
voidmerge(SeqlistL,intl,intr,intmid,intn){inttemp[n];
inti=l;intj=mid+1;intk=0;while(i<=mid&&j<=r){
if(L.elem[i]<=L.elem[j])
temp[k++]=L.elem[i++];
else {
temp[k++] =L.elem[j++];
}
}
while(i<=mid){temp[k++]=L.elem[i++];
}
while(j<=r){temp[k++]=L.elem[j++];
}
k=0;
while(l<=r)
{L.elem[l++]=temp[k++];}
showout(L);
printf("\n");
}
voidmerge_sort(SeqlistL,intl,intr){if(l>=r)return ;
intmid=(l+r)/2;
merge_sort(L,l,mid);merge_sort(L,mid+1,r);merge(L,l,r,mid,r-l+1);}
voidshowout(SeqlistL)
{
inti=0;
for (i=0; i<L.length; i++)
{
printf("%2d", L.elem[i]);
}
}
intmenu(){
system("cls");
printf("*********************\n");
printf("**请选择排序的方法****\n");
printf("**1.直接插入排序******\n");
printf("**2.冒泡排序*********\n");
printf("**3.简单选择排序*****\n");
printf("**4.快速排序*********\n");
printf("**5.归并排序*********\n");
printf("**0.退出*************\n");
printf("**请选择数字序号1-6**\n");
printf("********************\n");
}
intmain()
{
intn=0;
inta=0;
SeqlistLa;
La=Initlist();
printf("创建线性表,当输入-1时终止\n");
La=Create(La);
a=menu();
scanf("%d",&n);
while(n){
switch(n)
{
case1:
printf("经直接插入排序后线性表的元素为:\n");
InsertSort(La);
break;
case2:
printf("经冒泡排序后线性表的元素为:\n");
maopao(La);
break;
case3:
printf("经简单选择排序后线性表的元素为:\n");
SelectSort(La);
break;
case4:
printf("经快速排序后线性表的元素为:\n");
QuickSort(La,0,La.length-1);
break;
case5:
printf("经归并排序后线性表的元素为:\n");
merge_sort(La,0,La.length-1);
break;
default:
printf("输入错误,请重新输入\n");
break;
}
getch();
menu();
scanf("%d", &n);
}
return0;
}