冒泡排序和二分查找的练习。
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 | #include <stdio.h> #include <assert.h> #include <stdlib.h> /* srand rand */ #include <time.h> #include <unistd.h> static int binary(int arr[], const int size, const int n) { int high, low, mid; assert(arr != NULL); assert(size > 0); high = size - 1; low = 0; while (low <= high) { mid = (high + low) / 2; if (arr[mid] == n) { return mid; } else if (arr[mid] > n) { high = mid - 1; } else if (arr[mid] < n) { low = mid + 1; } } return -1; } static void maopao(int arr[], const int n) { int i, j, temp; assert(arr != NULL); assert(n > 0); for (i = 0; i < n; i++) { for (j = n - 1; j > i; j--) { if (arr[j] < arr[j-1]) { temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } } } static void print(const int arr[], const int n) { int i; for (i = 0; i < n; i++) { printf("%d,", arr[i]); } printf("\n"); } int main(void) { int arr[20]; int i; int b_ret, len; srand(time(NULL)); for (i = 0; i < 20; i++) { arr[i] = rand() % 100; } len = sizeof(arr)/sizeof(int); print(arr, len); maopao(arr, len); print(arr, len); b_ret = binary(arr, len, 47); if (b_ret != -1) { printf("47 is in %d\n", b_ret); } else { printf("don not exist!\n"); } return 0; } |
没有评论:
发表评论