數據結構之線性表的查找


話不多說,直接上代碼:

 1 #include "stdafx.h"
 2 #include<iostream>
 3 using namespace std;
 4 #define MAXSIZE 100
 5 
 6 int F[100];
 7 
 8 //無哨兵順序查找,a為數組,n為要查找的數組個數,key為要查找的關鍵字
 9 int Sequential_Search1(int *a, int n, int key)
10 {
11     for (int i = 1; i <= n; i++)
12     {
13         if (a[i] == key)
14             return i;
15     }
16     return 0;
17 }
18 
19 //有哨兵順序查找
20 int Sequential_Search2(int *a, int n, int key)
21 {
22     a[0] = key;
23     int i = n;
24     while (a[i] != key)
25     {
26         i--;
27     }
28     return i;
29 }
30 
31 //折半查找
32 int Binary_Search(int *a, int n, int key)
33 {
34     int low, high, mid;
35     low = 1;                      //定義最底下標為紀錄首位
36     high = n;                     //定義最高下標為記錄末尾
37     while (low <= high)
38     {
39         mid = (low + high) / 2;   //折半
40         if (key < a[mid])         //若查找的值比中值小
41             high = mid - 1;       //最高下標調整到中位下標小一位
42         else if (key > a[mid])    //若查找的值比中值打
43             low = mid + 1;        //最低下標調整到中位下標大一位
44         else                      
45         {
46             return mid;           //若相等則說明mid即為查找到的位置
47         }
48     }
49     return 0;
50 }
51 
52 int main()
53 {
54     int a[MAXSIZE + 1], result;
55     int arr[MAXSIZE] = { 0,1,16,24,35,47,59,62,73,88,99 };
56 
57     for (int i = 0; i <= MAXSIZE; i++)
58     {
59         a[i] = i;
60     }
61     result = Sequential_Search1(a, MAXSIZE, 100);
62     cout << "Sequential_Search1: " << result << endl;
63     result = Sequential_Search2(a, MAXSIZE, 1);
64     cout << "Sequential_Search2: " << result << endl;
65     result = Binary_Search(arr, 10, 62);
66     cout << "Binary_Search: " << result << endl;
67     return 0;
68 }

 

輸出如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM