C语言 二分法查找

tech2024-10-17  21

C语言 使用二分法查找

#include <stdio.h> #include<time.h> int fun(int *a, int k) { int low, high, mid; low = 0; high = 9; while(low <= high) { mid = (low + high)/2; if(k == a[mid]) return mid; if(k > a[mid]) { low = mid + 1; } if(k < a[mid]) { high = mid - 1; } } return mid; } int main(void) { srand(time); int a[10]; int i = 0, j, k, t = 0; while(i < 10) { a[i++] = rand() % 100 + 1; } // 选择排序 for(i = 0; i < 9; i++) { k = i; for(j = i + 1; j < 10; j++) { if(a[k] > a[j]) k = j; } //寻找最小的数 if(k != i) { t = a[i]; a[i] = a[k]; a[k] = t; //交换算法 } } // 输出 for(i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\n请输入要查找的值:\n"); scanf("%d", &j); printf("%d", fun(&a, j)); return 0; }
最新回复(0)