这是《数据结构与算法分析C语言描述》的22页相关内容编程。
#include<iostream>
using namespace std;
#define N 500
#define theNumber 83
#define NotFound -1
// generate random integer number
int * generateNumbers(int num)
{
int * data = (int *) malloc(sizeof(int)*num);
// cout<< "generated number is : ";
for(int i = 0; i < num; i++)
{
data[i] = random() % 100;
// cout<< data[i] << " ";
}
// cout<<endl;
return data;
}
// sort numbers
int * sortNumber(int * data, int num)
{
// int * sortedData = (int *)malloc(sizeof(int)*num);
// bubble sort algorithm
int tempData = 0;
for(int i = 0; i < num - 1; i++)
for(int j = 0; j < num - i - 1; j++)
{
if (data[j] > data[j + 1])
{
tempData = data[j];
data[j] = data[j + 1];
data[j + 1] = tempData;
}
}
// cout<<"sorted number is : ";
// for(int i = 0; i < num; i++)
// {
// cout<<data[i]<< " ";
// }
// cout<<endl;
return data;
}
// binary search, return the index in data sequence
int binarySearch(int * data, int number, int left, int right)
{
int index = -1;
if (left > right)
{
cout<< "system collapse!!"<<endl;
system("pause");
}
if (left == right && data[left] != number) return -1;
int center = (left + right) / 2;
if (data[center] == number)
return center;
else if(data[center] < number)
{
index = binarySearch(data, number, center + 1, right);
if(index == -1)
{
cout<<"the number not exits in the sequence"<< endl;
}
}
else if(data[center] > number)
{
index = binarySearch(data, number, left, center - 1);
if(index == -1)
{
cout<<"the number not exits in the sequence"<< endl;
}
}
return index;
}
// binary search algorithm in book
int binarySearchInBook(const int A[], int x, int n)
{
int low, mid, high;
low = 0;
high = n - 1;
while (low <= high)
{
mid = (low + high) / 2;
if(A[mid] > x)
{
high = mid - 1;
}
else if (A[mid] < x)
{
low = mid + 1;
}
else if (A[mid] == x)
{
return mid;
}
}
return NotFound;
}
int main()
{
// generate data
cout<<"generate data"<<endl;
int * numbers = generateNumbers(N);
// sort the numbers
cout<<"sort numbers"<<endl;
numbers = sortNumber(numbers, N);
// binary search
cout<<"binary search 1 "<<endl;
int index1 = binarySearch(numbers, theNumber, 0, N - 1);
cout<< "mothed one : final index iss\b " << index1 << endl;
cout<<"binary search 2 "<<endl;
int index2 = binarySearchInBook(numbers, theNumber, N);
cout<< "mothed two : final index is " << index2 << endl;
}