|
| 1 | +// |
| 2 | +// Created by ys on 2019年4月23日. |
| 3 | +// |
| 4 | + |
| 5 | +#include "LinklistSearch.h" |
| 6 | +#include "../tools.h" |
| 7 | + |
| 8 | +//线性查找元素 |
| 9 | +int SqListSearch(ElemType *SqList, int key, int len) { |
| 10 | + SqList[0] = key; |
| 11 | + int i = -1; |
| 12 | + for (i = len; SqList[i] != key; --i); |
| 13 | + return i; |
| 14 | +} |
| 15 | + |
| 16 | +void testSqlistSearch() { |
| 17 | + const int N = 1000; |
| 18 | + ElemType *SqList = (ElemType *) malloc(sizeof(ElemType) * (N + 1)); |
| 19 | + for (int i = 1; i <= N; ++i) { |
| 20 | + SqList[i] = randint(1, 10000); |
| 21 | + } |
| 22 | + |
| 23 | + ElemType key = 200; |
| 24 | + int i = SqListSearch(SqList, key, N); |
| 25 | + printf("%d\n", i); |
| 26 | + for (int i = 0; i <= N; ++i) { |
| 27 | + printf("%8d", SqList[i]); |
| 28 | + if (i % 10 == 0) { |
| 29 | + printf("\n"); |
| 30 | + } |
| 31 | + } |
| 32 | + free(SqList); |
| 33 | + SqList = NULL; |
| 34 | + |
| 35 | +} |
| 36 | + |
| 37 | +//折半查找 |
| 38 | +int BinSearch(ElemType *SqList, ElemType key, int low, int high) { |
| 39 | + int mid = -1; |
| 40 | + while (low <= high) { |
| 41 | + mid = (low + high) / 2; |
| 42 | + if(SqList[mid] == key) |
| 43 | + { |
| 44 | + return mid; |
| 45 | + } |
| 46 | + if(SqList[mid] > key) |
| 47 | + { |
| 48 | + high = mid - 1; |
| 49 | + } else |
| 50 | + { |
| 51 | + low = mid + 1; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return -1; |
| 56 | +} |
| 57 | + |
| 58 | +//折半查找递归算法 |
| 59 | +int RBinSearch(ElemType *SqList, int key, int low, int high) |
| 60 | +{ |
| 61 | + if(low > high) |
| 62 | + { |
| 63 | + return -1; |
| 64 | + } |
| 65 | + int mid = (low + high) / 2; |
| 66 | + if(SqList[mid] == key) |
| 67 | + { |
| 68 | + return mid; |
| 69 | + } |
| 70 | + |
| 71 | + if(SqList[mid] > key) |
| 72 | + { |
| 73 | + RBinSearch(SqList, key, low, mid - 1); |
| 74 | + } else |
| 75 | + { |
| 76 | + RBinSearch(SqList, key, mid + 1, high); |
| 77 | + } |
| 78 | + |
| 79 | +} |
| 80 | + |
| 81 | +void testBSearch() |
| 82 | +{ |
| 83 | + const int N = 1001; |
| 84 | + int *List = (int *)malloc(1001 * sizeof(int)); |
| 85 | + for (int i = 1; i < N; ++i) { |
| 86 | + List[i] = i; |
| 87 | + } |
| 88 | + int key = 74; |
| 89 | + |
| 90 | + int index = BinSearch(List, key, 1, N-1); |
| 91 | + |
| 92 | + printf("查找的index为:%d\n", index); |
| 93 | + index = RBinSearch(List, key, 1, N-1); |
| 94 | + printf("递归查找的index为:%d\n", index); |
| 95 | + |
| 96 | + free(List); |
| 97 | + List = NULL; |
| 98 | +} |
| 99 | + |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | + |
| 104 | + |
| 105 | + |
| 106 | + |
0 commit comments