靜態表查詢和二分法靜態表查詢
阿新 • • 發佈:2019-02-02
簡單的操作。。不解釋
#include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cmath> #include <algorithm> #include <cstring> #include <map> #include <sstream> #include <queue> #include <stack> #define INF 0x3f3f3f3f #define mem(a,b) memset(a,b,sizeof(a)); #define For(a,b) for(int i = a;i<b;i++) #define LL long long #define MAX_N 100010 using namespace std; typedef int ElemType; typedef struct // 靜態表結構體 { ElemType *elem; int length; }SStable; void Init_Table(SStable *ele) // 靜態表的初始化操作 { ele->elem = (ElemType *)malloc(sizeof(ElemType) * 100); ele->length = 0; return ; } void Insert_Table(SStable *ele) // 元素插入操作 { printf("請輸入一個整數:\n\n"); int n; scanf("%d",&n); cout<<endl<<"請輸入"<<n<<"個數作為查詢表的資料元素:"<<endl<<endl; for(int i = 0; i<n; i++) { int num; scanf("%d",&num); ele->elem[i+1] = num; ele->length ++; } return ; } void Sort_Sear_tab(SStable *ele) // 排序函式 { for(int i = 1; i<=ele->length-1; i++) { for(int j = i+1; j<=ele->length; j++) { if(ele->elem[i] > ele->elem[j]) { int temp = ele->elem[i]; ele->elem[i] = ele->elem[j]; ele->elem[j] = temp; } } } return ; } void Print_Table(SStable *ele) // 列印函式 { for(int i = 1; i<=ele->length; i++) { printf("%d ",ele->elem[i]); } cout<<endl<<endl; return ; } bool Equal(int num,int num1) // 判定相等的函式 { return (num == num1); } bool Less(int flag,int flag1) // 判定小於的函式 { return (flag<flag1); } int Search_Static(SStable *Sele,int S_num) // 靜態表查詢 { int i = Sele->length; Sele->elem[0] = S_num; for(i = Sele->length; !Equal(S_num,Sele->elem[i]); i--) ; return i; } int Search_Binary(SStable *Bele,int B_num) // 二分法靜態表查詢 { int left = 1,right = Bele->length; while(left <= right) { int mid = (left + right) / 2; if(Equal(B_num,Bele->elem[mid])) return mid; else if(Less(B_num,Bele->elem[mid])) right = mid - 1; else left = mid + 1; } return 0; } int main() { SStable head; Init_Table(&head); Insert_Table(&head); cout<<endl<<"該靜態查詢表中的資料元素是:"<<endl<<endl; Print_Table(&head); printf("請輸入資料通過靜態查詢法看其是否在靜態查詢表中:\n\n"); int num; scanf("%d",&num); int pos = Search_Static(&head,num); if(pos == 0) cout<<endl<<"資料 "<<num<<" 不存在於該靜態查詢表中。"<<endl<<endl; else cout<<endl<<"資料 "<<num<<" 在靜態查詢表中的下標是: "<<pos<<endl<<endl; Sort_Sear_tab(&head); printf("通過排序函式得到的有序靜態查詢表是:\n\n"); Print_Table(&head); printf("請輸入資料通過靜態查詢法看其是否在有序靜態查詢表中:\n\n"); int con; scanf("%d",&con); int pos1 = Search_Binary(&head,con); if(pos1 == 0) cout<<endl<<"資料 "<<con<<" 不存在於該靜態查詢表中。"<<endl<<endl; else cout<<endl<<"資料 "<<con<<" 在靜態查詢表中的下標是: "<<pos1<<endl<<endl; return 0; } /* 2016/12/18 Sunday 測試樣例: 10 2 5 9 10 6 3 11 7 29 4 3 11 */