问题描述:
一数组,含有一堆无序数据,首先将数据按顺序排列,再用二分法实现某个元素的查找,若找到,返回该元素在数组中的下表,否则,返回不存在提示信息。
#include<stdio.h> #include<stdlib.h> int *bubble_sort(int a[],int n)//冒泡排序(将数据升序排列) { int i; int j; int tmp; for(j=0;j<n-1;++j)//n个元素需要排序n-1趟 { for(i=0;i<n-j-1;++i)//第j趟需要比较n-j次,第一趟(j=0)需要比较n-1次,n-j-1 { if(a[i] > a[i+1]) { tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; } } } return a; } int binary_search(int b[],int n,int num)//二分法查找 { int left = 0; int right = n-1; int mid; while(left <= right) //若left <= right说明比较还未完成 { mid = (left + right)/2; if(num < b[mid])//所寻找元素在mid的左边 { right = mid -1; } else if(num > b[mid])//所寻找元素在mid的右边 { left = mid +1; } else { return mid; } } return -1;//left > right时说明比较完成后,仍未找到该元素 } int main() { system("mode con cols=100 lines=100"); system("color 0A"); int b[] = {34,45,23,13,57,85,37,10};//数组元素未排序 int n = sizeof(b)/sizeof(b[0]); int i; //循环因子 int num; //要寻找的元素 int ret; //接收二分法查找函数的返回值 bubble_sort(b,n); //二分法查找的前提,元素已经是有序的(将数组元素升序排列) for(i=0;i<n;i++) { printf("%d\n",b[i]); } printf("please input the num you want to find:\n"); scanf("%d",&num); ret = binary_search(b,n,num); if(ret == -1) { printf("it is not exist!\n"); } else { printf("it's subscript is %d\n",ret); } system("pause"); return 0; }
时间: 2024-10-15 01:04:48