Chinaunix首页 | 论坛 | 博客
  • 博客访问: 794794
  • 博文数量: 87
  • 博客积分: 2571
  • 博客等级: 少校
  • 技术积分: 726
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-19 15:04
个人简介

重新开始,做回自我,爱拼的男人最牛!

文章分类
文章存档

2021年(2)

2020年(3)

2019年(17)

2014年(1)

2011年(1)

2010年(63)

我的朋友

分类: WINDOWS

2010-10-28 22:31:44

在写一个简单程序时碰到这两个比较经典的算法:冒泡排序和折半查找,留下备用。
 
#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;
}
阅读(1619) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~