练习用c语言,按数据结构里的描述,写里面几种简单的排序。
#include <stdio.h>
#include <stdlib.h>
void BubbleSort(int a[],int len)
{
int i,j,temp;
for(i=0;i<len;i++)
{
for(j=len-1;j>i;j--)
{
if(a[j-1]>a[j])
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
for(int b=1;b<=len;b++)
{
printf("%d ",a[b-1]);
}
}
void SelectSort(int a[],int len)
{
int i,j,temp,min;
for(i=0;i<=len;i++)
{
min = i;
for(j=i+1;j<=len-1;j++)
{
if(a[j] < a[min])
{
min =j;
}
}
if(min != i)
{
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
for(int b=1;b<=len;b++)
{
printf("%d ",a[b-1]);
}
}
void InsertSort(int a[],int len)
{
int i,j,temp;
for(i=1;i<=len-1;i++)
{
int j=i-1;
if(a[i]<a[j])
{
for(;j<i;j--)
{
if(a[i]<a[j])
{
a[j+1]=a[j];
a[j]=a[i];
}
}
}
}
for(int b=1;b<=len;b++)
{
printf("%d ",a[b-1]);
}
}
void ShellSort(int a[],int len)
{
for(int d=len/2;d>1;d=d/2)
{
for(int i=0;i<=d;i++)
{
if(a[i]>a[i+d])
{
int temp;
temp=a[i];
a[i]=a[i+d];
a[i+d]=temp;
}
}
}
for(int b=1;b<=len;b++)
{
printf("%d ",a[b-1]);
}
}
void QuickSort(int a[],int len)
{
int low=0;
int high=len-1;
int key=low;
if(low!=high)
{
if(a[high]<a[key])
{
high--;
int temp;
temp=a[key];
a[key]=a[high];
a[high]=temp;
}
if(a[low]>a[key])
{
low++;
int temp;
temp=a[key];
a[key]=a[low];
a[low]=temp;
}
}
for(int b=1;b<=len;b++)
{
printf("%d ",a[b-1]);
}
}
int main()
{
printf("Hello Sort!\n");
int array[]={9,3,7,6,4,8,12};
int len = sizeof(array)/sizeof(int);
printf("待排序序列为:");
for(int b=1;b<=len;b++)
{
printf("%d ",array[b-1]);
}
printf("\n");
printf("待排序数组元素个数是:%d \n",len);
printf("冒泡排序:");
BubbleSort(array,len);
printf("\n");
printf("直接选择排序:");
SelectSort(array,len);
printf("\n");
printf("希尔排序:");
ShellSort(array,len);
printf("\n");
printf("快速排序:");
QuickSort(array,len);
printf("\n");
return 0;
}