zoukankan      html  css  js  c++  java
  • 折半查找

    #include<stdio.h>
    #include<stdlib.h>
    typedef int Status;
    Status binSearch(int *p,int key,int low,int high)
    {
    int middle;
    while(low<=high)
    {
    middle=(low+high)/2;
    if(p[middle]>key)
    {
    high=middle-1;
    }
    else if(p[middle]<key)
    {
    low=middle+1;
    }
    else
    {
    return middle;
    }
    }
    return 0;
    }
    void printArray(int *p,int m)
    {
    int i;
    for(i=0;i<m;i++)
    printf("%d ",*(p+i));
    }
    void bubbleSort(int *p,int m)
    {
    int i,j;
    for(i=1;i<m;i++)
    for(j=0;j<m-i;j++)
    {
    if(p[j]>p[j+1])
    {
    int tem;
    tem=p[j];
    p[j]=p[j+1];
    p[j+1]=tem;
    }

    }
    }
    int main()
    {
    int m,i,key,ret;
    printf("Please input the array size:");
    scanf("%d",&m);
    int *p=(int *)malloc(m*sizeof(int));
    printf("输入a[0]-a[%d]: ",m-1);
    for(i=0;i<m;i++)
    scanf("%d",p+i);
    printf(" ");
    printf("排序前: ");
    printArray(p,m);
    printf("排序后: ");
    bubbleSort(p,m);
    printArray(p,m);
    printf("please input the number value which you want to search: ");
    scanf("%d",&key);
    ret=binSearch(p,key,0,m-1);
    if(ret)
    {
    printf("The number %d is in %d position ",key,ret+1);
    }
    else
    {
    printf("The number %d is not exist ");
    }
    free(p);
    return 0;
    }

  • 相关阅读:
    C语言扩展题
    C语言第五题
    C语言第四题
    C语言第三题
    c语言第二题
    11
    游戏开发的一些想法
    openxml的视频教程
    JavaScript调试之console.log
    IPPatternConverter
  • 原文地址:https://www.cnblogs.com/loveyan/p/4556124.html
Copyright © 2011-2022 走看看