Okay I'm having trouble deciphering this program and how to do it. I've been tasked with adding code to implement function "search", which accepts an integer array of numbers, the array size and an integer value. The function returns true if the passed integer value is in the array and false if it isn't. This as far as I've gotten.
#include <iostream>
usingnamespace std;
bool search(int arr[], int size, int val);
constint SIZE =25;
int main()
{
int nums[SIZE]; // array declaration
bool found;
int n;
//initialize array nums
for (int i = 0; i < SIZE; i++)
{
nums[i] = rand( ) % 251;
}
// display the content of array nums
cout << "\n************************\n";
for (int i = 0; i < SIZE; i++)
{
cout << nums[i] << "\t";
}
cout << "\n************************\n";
cout << "please enter a number between 0 to 250" << endl;
cin >> n;
found = search(nums, SIZE, n);
if (found)
cout << n << " was found in our data set!\n";
else
cout << n << " was NOT found in our data set!\n";
return 0;
}
bool search(int arr[], int size, int val)
{
}
I'm not getting the answer I want and I was just wondering if someone could assist.
I am noticing that you aren't acutally using your search function--there is no code inside of it. I figure that you know this. Here is some pseudocode for a linear search:
1 2 3 4 5 6 7
bool search(int arr[], int size, int val)
{
//for each element (el) in array (arr):
//if( el == val ):
//return True;
// return False; // Not found
}
For your own edification, here is another search method that works way faster check out k-select (that's what I call it, but here they call it QuickSelect).
Here is some pseudo code:
1 2 3 4 5 6 7 8 9 10
function partition(list, left, right, pivotIndex)
pivotValue := list[pivotIndex]
swap list[pivotIndex] and list[right] // Move pivot to end
storeIndex := left
for i from left to right-1
if list[i] <= pivotValue
swap list[storeIndex] and list[i]
increment storeIndex
swap list[right] and list[storeIndex] // Move pivot to its final place
return storeIndex