【C++】随机生成数组->冒泡排序->二分查找

来源:互联网 发布:2013office软件下载 编辑:程序博客网 时间:2024/05/21 17:16

二分查找也属于顺序表查找范围,二分查找也称为折半查找。二分查找(有序)的时间复杂度为O(LogN)。

基本思想是, 在有序表中,取中间记录作为比较对象,若给定值与中间记录的关键字相等,则查找成功;若给定值小于中间记录的关键字,则在中间记录的左半区继续查找;若给定值大于中间记录的关键字,则在中间记录的右半区继续查找。不断重复上述过程,直到找到为止。

使用二分查找有两个前提条件:

1,待查找的列表必须有序,这里使用冒泡排序。

2,采用线性顺序存储结构来存储数据。

//程序源代码:/* 3.24 二分法(使用xxx)*//* Function: 从不定个随机数中找出某个数所在的位置索引 */#include <iostream>#include <vector>#include <time.h>#define MAX 101using namespace std;/* input function*/void fun_input( int num[] ) {int i;srand( (unsigned)time(NULL) );//用到time头文件for ( i = 1; i < MAX; i++ )num[i] = rand() % 100;}/* output function*/void fun_output( int num[] ){int i;for ( i = 1; i < MAX; i++ ){cout << num[i] << " ";if ( i % 10 == 0)  cout << endl;}}/* partition function*/void fun_bubbleSort( int num[], int low, int high ) {int i, j, temp;for ( i = low; i < high; i++ )for (j = i+1; j < high; j++){if ( num[i] > num[j] )  // 小的给num[i]{temp = num[i];num[i] = num[j];num[j] = temp;}}}/* Quick Sorting (for random array) function */void fun_findValue(int num[], int value, int low, int high)  {int pos_left,pos_right;int found = 0;while ( low < high ){int mid = (low + high)/2;if ( num[mid] == value ){found = 1;pos_left  = mid;pos_right = mid;while (num[pos_left-1] == num[pos_left])pos_left--;while (num[pos_right+1] == num[pos_right])pos_right++;}if ( num[mid] < value )low = mid + 1;elsehigh = mid - 1;}if (found){cout << endl << " Ok! 要查找的数字存在 " << pos_right-pos_left+1 << " 个" << endl;cout << "     位置分布于 " << pos_left << " 到 " << pos_right << endl;}elsecout << "sorry! 你要查找的数字不存在。" << endl;}void main(){   int value, num[MAX];   time_t start, end;   time( &start );  // tic   fun_input(num);  cout << endl << "随机产生一个10*10矩阵:" << endl;cout << "-------------------------------" << endl;   fun_output(num);   cout << "-------------------------------" << endl;   fun_bubbleSort(num, 0, MAX - 1);  cout << endl << "冒泡排序后变为如下10*10矩阵:" << endl;cout << "-------------------------------" << endl;   fun_output(num);        cout << "-------------------------------" << endl;cout << endl << "请输入要查找的数字:" << endl;cin >> value;fun_findValue(num, value, 0, MAX - 1);  time( &end );  // toccout << "已运行:" << end-start << "s" << endl;system("pause");}