在写一个简单程序时碰到这两个比较经典的算法:冒泡排序和折半查找,留下备用。
#include "stdafx.h"
#include
#include
#define N 10
int main(int argc, char* argv[])
{
int array[N],i,j,number,low,high,mid;
char ch;
printf("The original array is:");
for(i=1;i {
array[i]=rand()%100; /*产生并显示N-1个0~99的随机整数,存放在数组[1]~[N-1]单元中*/
printf("%3d",array[i]);
}
printf("\n");
/*冒泡法排序*/
for(i=1;i
for(j=1;j if(array[j] {
array[0]=array[j];
array[j]=array[j+1];
array[j+1]=array[0];
}
/*显示排序后的数列*/
printf("The sorted array is:");
for(i=1;i printf("%3d",array[i]);
printf("\n");
/*折半查找,可进行多次*/
while(1)
{
printf("\nPlease input the number which you want to look for:");
scanf("%d",&number);
low=1;
high=N-1;
while(low<=high)
{
mid=(low+high)/2;
if(array[mid]==number)
{
printf("%d has been found at position %d.\n",number,mid);
break;
}
else if(number
low=mid+1;
else
high=mid-1;
}
if(low>high)
printf("Can not find %d.\n",number);
printf("Do you want to find another number?(Y/y):");
scanf(" %c",&ch); /*注意%c前面有一个空格,为了虑除以前的回车符,否则循环只能执行一次*/
if(ch!='Y' && ch!='y')
break;
}
return 0;
}
阅读(1677) | 评论(0) | 转发(0) |