1. The program first creates an array of 20 random positive numbers between 1 and 100. Make sure there
are no duplicates in the array.
2. Then apply selection sort to sort the array in ascending order, then display the entire array.
3. Now, ask user to enter any number between 1 and 100.
4. Use binary search to check if the user’s number is contained in the array. If so, display ‘yes’ with the
index of the matching element. If not, display ‘no’.
5. Ask if the user wants to continue. If yes, return to Step 3. If no, terminate program.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
void sort(int a[], int n);
void print5(int a[]);
int binarySearch (int arr[], int value, int size);
constint ArraySize = 20;
int arr[ArraySize];
int main()
{
int numberEntered;
srand(time(NULL));
for (int i = 0; i < ArraySize;i++) {
arr[i] = (2 * rand() % 100);
}
sort(arr,ArraySize);
print5(arr);
cout << "Please enter a number:" << endl;
cin >> numberEntered;
int search = binarySearch(arr, ArraySize, numberEntered);
if (search == -1)
cout << "That number was not found";
else {
cout << "That number is found at element: " << arr << endl;
}
return 0;
}
int binarySearch(int arr[], int value, int size, int right, int left) {
while (left <= right) {
int middle = (left + right) / 2;
if (arr[middle] == value)
return middle;
elseif (arr[middle] > value)
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
void sort(int a[], int n)
{
int temp;
for (int x = 1; x <= n ; x++)
{
for (int i = 0; i+1 < n; i++)
{
if (a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
}
void print5(int a[])
{
for (int c = 0; c < 20; c++)
{
cout << a[c] << endl;
}
}
Here is the error:
1 2 3
/tmp/ccFLEPP7.o: In function `main':
:(.text.startup+0x99): undefined reference to `binarySearch(int*, int, int)'
collect2: error: ld returned 1 exit status
Could someone help me and tell me what I'm doing wrong? I've tried everything and can't seem to make it work.
int binarySearch (int arr[], int value, int size); //line 9, declaration
int search = binarySearch(arr, ArraySize, numberEntered); //line 29, function call
int binarySearch(int arr[], int value, int size, int right, int left) //line 40, definition
the prototypes don't match, you added `right' and `left' parameters (¿what for?).
> The reason I did that was that the binarySearch called left and right integers
don't understand what you're saying, please rephrase.
If you do need `left' and `right' they should be in the declaration and the calling should fill their values.