jQuery火箭图标返回顶部代码

数据结构之线性表的查找

话不多说,直接上代码:

 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 }

 

输出如下:

posted @ 2018-05-12 20:24  迷途纸鸢  阅读(1881)  评论(0编辑  收藏  举报