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
|
// This program performs a linear search on a character array
#include <iostream>
using namespace std;
int searchList( const int[], int, int); // function prototype
void selectionSort(int[], int); // function prototype
const int SIZE = 8;
int main()
{
int num[SIZE] = {3, 6, -19, 5, 5, 0, -2, 99};
int found;
int numb;
selectionSort (num, SIZE);//To sort the array because its a binary search
cout << "Enter a number to search for:" << endl;
cin >> numb;
found = searchList(num, SIZE, numb);
if (found == -1)
cout << "The number " << numb
<< " was not found in the list" << endl;
else
cout << "The number " << numb <<" is in the " << found
<< " position of the list" << endl;
return 0;
}
//***********************************************************
// Selection Sort
//***********************************************************
void selectionSort(int num[], int SIZE)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (SIZE - 1); startScan++)
{
minIndex = startScan;
minValue = num[startScan];
for(int index = startScan + 1; index < SIZE; index++)
{
if (num[index] < minValue)
{
minValue = num[index];
minIndex = index;
}
}
num[minIndex] = num[startScan];
num[startScan] = minValue;
}
}
//*******************************************************************
// searchList
//
// task: This searches an array for a particular value
// data in: List of values in an array, the number of
// elements in the array, and the value searched for
// in the array
// data returned: Position in the array of the value or -1 if value
// not found
//
//*******************************************************************
int searchList( const int num[], int SIZE, int numb)
{
int found = -1;
for (int count = 0; count <= SIZE; count++)
{
if (num[count] == numb)
{
found = count;
return found;
}
}
return found;
}
|