zoukankan      html  css  js  c++  java
  • 二分查找(利用选择排序)-简单

    源程序:

    //二分查找法
    #include <stdio.h>
    #define MaxSize 8
    typedef struct
    {
      int stuno;
      char stuname[20];
    }TableElem;

    TableElem stu[]={{1001,"zhang"},{1009,"wang"},{2005,"sun"},{2008,"liu"},{3001,"zheng"},
    {3005,"lai"},{4003,"qin"},{4400,"ren"}};

    typedef struct
    {
      TableElem elem[MaxSize];
      int n;
    }SqTable;

    //二分查找函数
    int bin_search(SqTable T,int key)
    {
      int low,high,mid;
      low=1;
      high=T.n;

      while(low<high)
      {
        mid=(low+high)/2;
        if(T.elem[mid].stuno==key)
          return mid;
        else if(key<T.elem[mid].stuno)
          high=mid-1;
        else
          low=mid+1;
      }
      return 1;
    }
    /*
    int searchsqtable(SqTable T,int key) //查找函数
    {
      T.elem[0].stuno=key;
      int i=T.n;
      while(T.elem[i].stuno!=key)
        i--;
      return i;
    }
    */
    //选择排序
    void select_sort(SqTable T,int nn)
    {
      int min,i,j;
      TableElem temp;
      for(i=0;i<nn-1;i++)
      {
        min=i;
        for(j=i+1;j<nn;j++)
        {
          if(T.elem[j].stuno<T.elem[j+1].stuno)
            min=j;
        }
        if(min!=j)
        {
          temp=T.elem[min];
          T.elem[min]=T.elem[i];
          T.elem[i]=temp;
        }
      }
    }
    int main()
    {
      SqTable seq;
      for(int i=0;i<MaxSize;i++)
      {
        seq.elem[i]=stu[i]; //用stu[8]8个人初始化elem[8]数组
      }
      seq.n=MaxSize;
      //8个人按学号排序
      int n=MaxSize;
      select_sort(seq,n);

      for(i=0;i<MaxSize;i++)
        printf("%d %s ",seq.elem[i].stuno,seq.elem[i].stuname);

      int kk,mm;
      printf("请输入要查找的学号:");
      scanf("%d",&kk);
      mm=bin_search(seq,kk); //调用查找函数
      printf("此人在顺序表中的位置是:%d ",mm+1);
      printf("%d号的姓名为:%s ",mm+1,seq.elem[mm].stuname);
      return 1;
    }

     

  • 相关阅读:
    PHP版本VC6与VC9/VC11/VC14、Thread Safe与None-Thread Safe等的区别
    Django 开发------django-crontab实现服务端的定时任务
    django HTML 数据处理
    HTML 罗盘式时钟
    Tcpdump 常用命令、参数记录
    jquery 实现 <imput>标签 密码框显示/隐藏密码功能
    Django 实现分页功能(django 2.2.7 python 3.7.5 )
    bootstrap 4 学习笔记
    IIS属性解析
    IIS站点权限设置
  • 原文地址:https://www.cnblogs.com/duanqibo/p/11904012.html
Copyright © 2011-2022 走看看