1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include <stdio.h> #include <stdlib.h> #include <time.h>
typedef int ElemType; typedef struct { ElemType *elem; int length; } SSTable;
void initSSTable(SSTable &S, int length) { S.length = length + 1; S.elem = (ElemType *) malloc(sizeof(ElemType) * S.length); int i; srand(time(NULL)); for (i = 1; i < S.length; i++) { S.elem[i] = rand() % 100; } }
void printST(SSTable S) { for (int i = 1; i < S.length; i++) { printf("%3d", S.elem[i]); } printf("\n"); }
int selSSTable(SSTable S, ElemType e) { S.elem[0] = e; int i;
for (i = S.length - 1; i >= 0; i--) { if (S.elem[i] == e) { return i; } } return -1; }
int binarySearch(SSTable L, ElemType key) { int low = 0, mid, high = L.length - 1; while (low <= high) { mid = (low + high) / 2; if (L.elem[mid] == key) { return mid; } else if (L.elem[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; }
int compare(const void *left, const void *right) { return *(ElemType *) left - *(ElemType *) right; }
int main() { SSTable S; initSSTable(S, 10); printST(S); ElemType key; printf("请输入要查询的元素\n"); scanf("%d", &key); int index = selSSTable(S, key); if (index) { printf("查找元素的位置为:%d\n", index); } else { printf("没有找到"); }
qsort(S.elem, S.length, sizeof(ElemType), compare); printf("排序后的顺序是\n"); printST(S); printf("请输入要查询的值\n"); scanf("%d", &key); int ret = binarySearch(S, key); if (ret != -1) { printf("查找成功 位置为 %d\n", ret); } else { printf("查找失败\n"); } return 0; }
|