1. 程式人生 > >順序查找和二分查找代碼

順序查找和二分查找代碼

malloc pan maxsize inpu struct keys int ted print

/*************************************************************************
    > File Name: StaticSearchTable.c
    > Author: 
    > Mail: 
    > Created Time: Fri 21 Dec 2018 03:49:17 PM CST
 ************************************************************************/

#include<stdio.h>
#define
MAXSIZE 20 typedef int keytype; //自定義關鍵字類型為整型 typedef struct { keytype key; }ElemType; typedef struct { ElemType *elem; int length; }stable; void cretable(stable *Q) { int i; keytype x; Q->elem = (ElemType *)malloc(sizeof(ElemType)*(MAXSIZE+1)); printf("Input keys(-1:End):
"); scanf("%d",&x); i = 0; while(x!=-1 && i<MAXSIZE) { i++; Q->elem[i].key = x; scanf("%d",&x); } Q->length = i; } void list(stable *Q) { int i; for(i=1;i<=Q->length;i++) { printf("%5d",i); } printf(
"\n"); for(i=1;i<=Q->length;i++) { printf("%5d",Q->elem[i].key); } printf("\n"); } //順序查找 int seqsearch1(stable *ST,keytype key) { int i; for(i=ST->length;i>0;i--) { if(ST->elem[i].key==key)return i; } return 0; } //為了避免查找過程中每一步都要檢測整個表是否查找完畢,查找之前先將key付給ST->elem[0]的關鍵字。 //改進後如下 int seqsearch2(stable *ST,keytype key) { int i; ST->elem[0].key = key; for(i=ST->length;ST->elem[i].key!=key;i--); return i; } //二分查找 int binsearch(stable *ST,keytype key) { int low = 1,high = ST->length,mid; while(low<=high) { mid = (low + high)/2; if(ST->elem[mid].key==key)return mid; if(key<ST->elem[mid].key) high = mid - 1; else low = mid + 1; } return 0; }

順序查找和二分查找代碼