排序及查找要领
#include <malloc.h>
#include<stdio.h>
#define N 11
/*用监督哨查找*/
int search(int array[],int n,int k)
{int i;
i=n-1;
array[0]=k;
while(array[i]!=k) i--;
return(i);
}
/*折半查找法*/
int halfsearch(int array[],int n,int k)
{int i,j,mid;
i=1;j=n;
while(i<=j)
{mid=(i+j)/2;
if(k==array[mid]) return(mid);
else if(k<array[mid]) j=mid-1;
else i=mid+1;
}
return(0);
}
/*冒泡排序法*/
void mpsort(int array[])
{int i,j,a;
a=0;
for(i=1;i<N;i++)
for(j=i+1;j<N;j++)
if(array[i]>array[j])
{a=array[i];
array[i]=array[j];
array[j]=a;}
}
/*直接插入排序*/
void insertsort(int array[])
{int i,j;
for(i=2;i<N;i++)
{array[0]=array[i];
j=i-1;
while(array[0]<array[j])
{array[j+1]=array[j--];
array[j+1]=array[0];
}
}
}
/*成立*/
void creat(int array[])
{int i;
printf("enter the array:\n");
for(i=1;i<N;i++)
scanf("%d",&array[i]);
}
/*显示*/
void print(int array[])
{int i;
printf("The numbers after sort is:\n");
for(i=1;i<N;i++)
printf("%d ",array[i]);
printf("\n");
}
main()
{int a[11],i,x,chang;
/*printf("enter the array\n");
for(i=1;i<11;i++)
scanf("%d",&a[i]);*/
/* www.bianceng.cn */
aga:
printf("\nchang:1: use watching method finding\n 2:use half method finding\n 3: use directness intsert method sort\n 4:use bubble up method sort\n 5:exit\n");
scanf("%d",&chang);
switch (chang)
{case 1:
{creat(a);
printf("Please int the search number:\n");
scanf("%d",&x);
printf("The number station is:%d\n",search(a,N,x));
goto aga;
}
case 2:
{ creat(a);
insertsort(a);
print(a);
printf("Please int the search number:\n");
scanf("%d",&x);
printf("The number station is:%d\n",halfsearch(a,N,x));
goto aga;
}
case 3:
{creat(a);
insertsort(a);
print(a);
goto aga;
}
case 4:
{creat(a);
mpsort(a);
print(a);
goto aga;
}
case 5:{ printf("exit!\n");break;}
default:{printf("Error!\n"); goto aga;}
}
}