void InsertSort(int *a,int length)
{
int i,j,temp;
for(i=1;i<length;i++) { temp = a[i]; for(j=i-1;j>=0;j--) { if(temp < a[j]) { a[j+1] = a[j]; } else break; } a[j+1] = temp; }
}
for一个成员放temp
小弟来交换,还要再循环
大哥就罚站
void ShellSort(int *a,int length)
{
int i,j,h,temp;
for(h=length/2;h>0;h/=2)
{
for(i=h;i<length;i++)
{
temp = a[i];
for(j=i-h;j>=0;j-=h)
{
if(temp < a[j])
a[j+h] = a[j];
else
break;
}
a[j+h] = temp;
}
}
}
void BubbleSort(int *a,int length)
{
int temp;
for(int i=0;i<length-1;i++)
{
for(int j=0;j<length-1-i;j++)
{
if(a[j+1] < a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
void QuickSort(int *a,int start,int end)
{
if(start>=end)
return;
int x = start;
int y = end;
int base = a[start];
while(x<y)
{
while(a[y] > base && x<y)
{
y–;
}
if(x < y)
{
a[x++] = a[y];
}
while(a[x] < base && x<y) { x++; } if(x < y) { a[y--] = a[x]; } a[x] = base; QuickSort(a,start,x-1); QuickSort(a,x+1,end); }
}
你比我小我向前(y–)
你比我大我给它(a[x]=a[y])
它无办法向后挪
重合以后劫base
你去调来我也调
void SelectSort(int *a,int length)
{
int min;
for(int i=0;i<length;i++)
{
min = i;
for(int j=i+1;j<length;j++)
{
if(a[min] > a[j])
{
min = j;
}
}
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
循环最小我记号
原始位置变最小
然后就是下一位
void ScanArray(int *a,int length)
{
for(int i=0 ; i<length ; i++)
{
printf("%d ",a[i]);
}
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[] = {5,5,6,8,1,7,6,8,4,5,2};
int e[] = {5,5,6,8,1,7,6,8,4,5,2};
int f[] = {5,5,6,8,1,7,6,8,4,5,2};
//int *b = a; //InsertSort(b,sizeof(b) / sizeof(b[0])); //ScanArray(b,sizeof(b) / sizeof(b[0])); printf("希尔排序;\n"); //int *c = a; //ShellSort(c,sizeof(a) / sizeof(a[0])); //ScanArray(c,sizeof(a) / sizeof(a[0])); printf("冒泡排序;\n"); int *d = a; BubbleSort(d,sizeof(a) / sizeof(a[0])); ScanArray(d,sizeof(a) / sizeof(a[0])); printf("\n"); printf("快速排序;\n"); QuickSort(e,0,sizeof(a) / sizeof(a[0]) - 1); ScanArray(e,sizeof(a) / sizeof(a[0])); printf("\n"); printf("快速排序;\n"); SelectSort(f,sizeof(a) / sizeof(a[0])); ScanArray(f,sizeof(a) / sizeof(a[0])); printf("\n"); return 0;
}