1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <iostream>
using namespace std;
int Function1(double array1[]);
void sort(double array1[], int count);
int bsearch(double array1[], int count, double key);
void PrintArray(const double array1[], int count);
const int MAXSIZE = 100;
int main()
{
double array1[100], key(0);
int count;
count = Function1(array1);
sort(array1, count);
bsearch(array1, count, key);
cout<<"There were "<<count<<" numbers entered into the array."<<endl;
PrintArray(array1, count);
return 0;
}
int Function1(double array1[])
{
int i = 0;
double somenumber;
do
{
cout<<"Please enter a number to enter into the array or a negative number to stop."<<endl;
cout<<"You should enter the numbers in ascending order.\n";
cin>>somenumber;
if (somenumber >= 0)
{
do
{
array1[i] = somenumber;
i++;
cin>>somenumber;
}
while (somenumber >= 0);
}
}while (i < MAXSIZE && somenumber >=0);
return i;
}
void sort(double array1[], int count)
{
int b;
double temp;
for (int a=0; a <= count-2; ++a)
{
b = a;
for (int c=a+1; c <= count-1; ++c)
{
if (array1[c] < array1[b])
b = c;
}
temp = array1[b];
array1[b] = array1[a];
array1[a] = temp;
}
}
int bsearch(double array1[], int count, double key)
{
int high=count-1, low=0, middle;
while (low <= high)
{
middle = (low+high)/2;
if (key == array1[middle])
{
return middle;
}
else if (key , array1[middle])
{
high = middle-1;
}
else
{
low = middle+1;
}
}
return -1;
}
void PrintArray(const double array1[], int count)
{
for(int i = 0; i < count; i++)
{
cout<<array1[i]<<endl;
}
}
|