#include<stdio.h>
#include<stdlib.h>
int m[] = {10,9,8,2,3,1};
int i = 0;
int N = 6;
void BubbleSort(int a[],int N)
{
int flag = 0;
int mid = 0;
int i =0,j = 0;
for(i = 0; i<N-1;i++)
{
for(j = N-1; j>i ;j--)
{
if(a[j-1] >a[j])
{
mid = a[j-1];
a[j-1] = a[j];
a[j] = mid;
flag = 1;
}
}
if(!flag) //如果某趟没有 交换,自此退出,全部排序完毕
return ;
}
}
void QuickSort(int a[],int l,int r)
{
if(l<r)
{
int x = a[l];
int i = l;
int j = r;
while(i < j)
{
while(i<j && x>=a[j])
{
j--;
}
if(i<j)
a[i++] = a[j];
while(i<j && x <a[i])
{
i++;
}
if(i<j)
a[j--] = a[i];
}
a[i] = x;
QuickSort(a,l,i-1);
QuickSort(a,i+1,r);
}
}
//直接插入排序
void DirectInsertSort(int a[],int N)
{
int i = 0;
int m = 0;
int j = 0;
for(i=1;i<N;i++) //注意,这个容易出现数据越界的问题
{
if(a[i-1]>a[i])
{
m = a[i];
j = i;
do
{
a[j] = a[j-1];
j--;
}while(j>0 && a[j]>m);
a[j] = m;
}
}
}
void ShellSort(int a[],int N)
{
int inc =N;
int i = 0;
int m = 0;
int j = 0;
for(;inc >=1 ;inc =inc /3)
{
for(i=inc;i<N;i+=inc)
{
if(a[i-inc]>a[i])
{
m = a[i];
j = i;
do
{
a[j] = a[j-inc];
j = j - inc;
}while(j>0&& a[j]>m);
a[j] = m;
}
}
}
}
//直接选择排序
void DirectChoice(int a[], int N)
{
//int m,n,i,j=0;这样还是不行的,变量没有都初始化的
int m=0,n=0,i=0,j=0;
for(i = 0;i<N;i++)
{
m = i;
for(j=i+1;j<N;j++)
{
if(a[m]>a[j]) //作为数组,若是M是没有被初始化的,就容易产生段错误
m = j;
}
if(m != i)
{
n = a[m];
a[m] = a[i];
a[i] = n;
}
}
}
void print()
{
for( i = 0;i<N;i++)
printf("%d ",m[i]);
printf("\n");
}
int main()
{
BubbleSort(m,N);
printf("\nafter BubbleSort : ");
print();
QuickSort(m,0,5);
printf("\nafter QuickSort : ");
print();
DirectInsertSort(m,N);
printf("\nafter DirectInsertSort : ");
print();
ShellSort(m,N);
printf("\nafter ShellSort : ");
print();
DirectChoice(m,N);
printf("\nafter DirectChoiceSort : ");
print();
return 0;
}