Help with Search and Sort Algorithms

I have an assignment that says "Your main function should call the function to input elements into the array, call the function to print the contents of the array, call the function to search the array, and then print the location of the found element (if applicable). If the element was not found in the array, then there should be a printout to indicate that."

I'm not sure how to call the function to search the array. I assume the professor means the program should ask the user for a value he or she would like to search for. Based on the code below it seems like the program skips over the binary search function. Maybe I have the wrong idea of how binary search works or what it's used for.


Here is the code.

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;
	}
}
Last edited on
Topic archived. No new replies allowed.