【问题描述】
生成一个随机数组A[64] ,在数组中查找是否存在某个数num。
【答案】
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> //普通查找: int Search(int *p, int n, int num) //找到返回下标,未找到返回-1 { for (int i = 0; i < n; i++) { if (p[i] == num) return i; } return -1; } //冒泡排序: void Sort(int *p, int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (p[j] > p[j+1]) { int tmp = p[j]; p[j] = p[j + 1]; p[j + 1] = tmp; } } } } //二分查找: int BinarySearch(int *p, int n, int num) { int low, high, mid; low = 0; high = n - 1; mid = (low + high) / 2; while (low <= high) { if (num == p[mid]) return mid; else if (num < p[mid]) { high = mid - 1; mid = (low + high) / 2; } else { low = mid + 1; mid = (low + high) / 2; } } return -1; } void main() { int a[64]; time_t tms; srand((unsigned int)time(&tms)); //生成随机数种子 for (int i = 0; i < 64; i++) { a[i] = rand() % 100; //0~100之间的随机数 printf("%d ", a[i]); } //int num; //printf("请输入要查找的数: "); //scanf("%d", &num); int ret; //ret = Search(a, 64, num); Sort(a, 64); printf("排序后: "); for (int i = 0; i < 64; i++) printf("%d ", a[i]); int num; printf("请输入要查找的数: "); scanf("%d", &num); ret = BinarySearch(a, 64, num); if (ret == -1) printf("未找到! "); else printf("找到a[%d]=%d ",ret,num); system("pause"); }