search1.cpp

来自「这是我学习数据结构时用过的程序。索性打包传上去。数据结构实验用。」· C++ 代码 · 共 63 行

CPP
63
字号
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

typedef int keyType;

typedef int ElemType;

typedef struct{
  ElemType *elem;
  int length; 
}SSTable;

int Create(SSTable &ST,int n){
  int i;
  int x=0;

  ST.elem=(ElemType*)malloc((n+1)*sizeof(ElemType));
  printf("请输入9个数:");
  for(i=1;i<=n;i++){
	  scanf("%d",&x);
    ST.elem[i]=x;
  }
  ST.length=n;
  return 1;
}

int Search_Seq(SSTable ST,keyType key){
   int i;
   ST.elem[0]=key;
   for(i=ST.length;ST.elem[i]!=key;--i);
   
   return i;
}


int Search_Bin(SSTable ST,keyType key){
    ElemType low,high,mid;
    low=1;high=ST.length;
    while(low<=high){
       mid=(low+high)/2;
       if (key==ST.elem[mid]) return mid;
       else if (key<ST.elem[mid]) high=mid-1;
       else low=mid+1;
    }
    return 0;
}


main(){
   
   SSTable ST;
   int i;
   Create(ST,9);  //9个数
   
   i=Search_Seq(ST,5);
   printf("5是序列中的第%d个\n",i);

   i=Search_Bin(ST,7);
   printf("7是序列中的第%d个\n",i);
   
   return 1;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?