查找
顺序表的顺序及二分查找:
#include<stdio.h> #include<stdlib.h> typedef int Position; typedef int ElementType; typedef struct LNode *PtrToLNode; #define MAXSIZE 10 struct LNode{ ElementType Data[MAXSIZE]; Position Last; }; typedef PtrToLNode List; List MakeEmpty(){ List P; P = (List)malloc(sizeof(struct LNode)); P->Last = -1; return P; } bool Insert(List L,Position n,ElementType x){ if(L->Last == MAXSIZE - 1) { printf("表满"); return false; } if(n<1 || n>L->Last+1+1){ printf("位序不合法"); return false; } for(int j = L->Last;j>=n-1;j--) { L->Data[j+1] = L->Data[j]; } L->Data[n-1] = x; L->Last++; return true; } bool Delete(List L,Position n){ if(L->Last == MAXSIZE - 1) { printf("表满"); return false; } if(n<1 || n>L->Last+1){ printf("位序不合法"); return false; } for(int j = n-1;j<L->Last+1;j++) { L->Data[j] = L->Data[j+1]; } L->Last--; return true; } int Length(List L){ return L->Last+1; } int Printf(List L){ for(int i = 0 ; i<L->Last+1;i++) printf("%d ",L->Data[i]); printf("\n"); return 0; } //=======查找======= Position Find(List L,ElementType x){ int j; for( j = 0;j<L->Last+1;j++) { if(x == L->Data[j]) { printf("查找的下表%d位序为:%d\n",L->Data[j],j+1); return 0; } } if(j >= L->Last) { printf("查找的不存在"); } return 0; } //=======顺序查找======= Position SequentialSerch(List Tb1,ElementType K){ Position i; Tb1->Data[0] = K; for(i = Tb1->Last;Tb1->Data[i] != K;i--); return i+1; } //=======二分查找======= Position BinarySearch(List Tb1,ElementType K){ Position left,right,mid; left = 1; mid = 0; right = Tb1->Last; while(left<=right){ mid = (left + right)/2; if( K < Tb1->Data[mid]) right = mid-1; else if(K>Tb1->Data[mid]) left = mid+1; else return mid+1; } return 0; } int main(){ List L; L = MakeEmpty(); for(int i =1;i<11;i++) Insert(L,i,i); Printf(L); printf("表长:%d\n",Length(L)); Find(L,4); printf("顺序查找4的位置为:%d\n",SequentialSerch(L,4)); printf("二分查找4的位置为:%d\n",BinarySearch(L,4)); return 0; }