zoukankan      html  css  js  c++  java
  • 数组排序后二分查找

    对一个无序的数组中的关键字进行排序,排序完毕后用二分查找的方式对某一个特定的关键字进行查找。

    代码:

    #include<stdio.h>
    int n;
    struct num
    {
     int date;//数据域 
     int p;   //记录数据的初始位置 
    }num[100];
    struct num temp;

    void Inital()//输入数据 
    {
      int i;
      printf("Please input n:\n");
      scanf("%d",&n);
      printf("Please input %d numbers:\n",n);
      for(i=1;i<=n;i++)
      {
      scanf("%d",&num[i].date);
      
      num[i].p=i; //当前位置 
      }
    }
    void BubbleSort(int n)//Bubble sort
    {
     int i,j,k,index;
     
     for(i=1;i<n;i++)
      for(j=0;j<n-i;j++)
       if(num[j].date>num[j+1].date)
       {
       temp=num[j];
       num[j]=num[j+1];
       num[j+1]=temp;

     }

    }
    /*void SelectSort(int n)//Select sort
    {
     int i,j,k,index;
     for(i=0;i<n-1;i++)
     {
      index=i;
      for(j=i+1;j<n;j++)
       if(num[j].date<num[index].date)
       index=j;

       temp=num[j];
       num[j]=num[index];
       num[index]=temp;

     }

    }
    */
    int SecSearch(int x)//二分查找 
    {
     int low,high,i,mind;
     low=0;
     high=n-1;
     while(low<=high)
     {
      mind=(low+high)/2;
      if(num[mind].date==x)
      return num[mind].p;
      if(num[mind].date>x)
      high=mind-1;
      if(num[mind].date<x)
      low=mind+1;

     }
     return 0;
    }

    int main()
    {
      int x,point,i;
      Inital();
      BubbleSort(n);
      printf("The new array is:\n");
      for(i=1;i<=n;i++)
      {
       printf("%3d",num[i].date);
      }
      printf("\n");
      printf("Please input the number you want to search:\n");
      scanf("%d",&x);
      point=SecSearch(x);
      if(point)
      {
      printf("%d at the %d seat of the arrey!\n",x, point);    
      } 
      else
      {
          printf("Can't find number %d!\n",x);
      }

      return 0;

    }
    /*
    Please input n:
    10
    Please input 10 numbers:
    12 45 7 14 2 9 3 46 19 46
    The new array is:
      2  3  7  9 12 14 19 45 46 46
    Please input the number you want to search:
    14
    14 at the 4 seat of the arrey!
    Press any key to continue...
    */
  • 相关阅读:
    Es module vs require
    phaser3 画虚线实现
    新的计划
    [转]Boostrap Table的refresh和refreshOptions区别
    Storing Java objects in MySQL blobs
    【转】Ubuntu下搜狗输入法突然无法输入中文
    团队作业六
    团队作业七
    团队作业四
    团队作业三
  • 原文地址:https://www.cnblogs.com/lanshy/p/2978278.html
Copyright © 2011-2022 走看看