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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream>
#include <fstream>
#include <string>
#include <array>
using namespace std;
constexpr int SIZE{ 200 };
int binarySearch(int array[], int size, int value);
void selectionSort(int array[], int size);
int main()
{
// prompt user to enter file name. also display if it exists or not
ifstream inputFile; // gives access to file
string name, filename;
int numbers[SIZE] {};
int count{};
// Get file name from the user
cout << "Enter the file name: ";
cin >> filename;
// Open the file
inputFile.open(filename.c_str());
// If the file opened successfully, process it
if(!inputFile)
{
// display an error message if the file was not found
cout << "Error opening the file.\n";
return 1;
}
// read the #'s from the file & display them.
while(count < SIZE && inputFile >> numbers[count])
{
count++;
}
// close the file
inputFile.close();
// sort the array using selection sort
{
void selectionSort(int array[], int size);
}
int startScan, minIndex, minValue;
for(startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan + 1; index < size; index++)
{
if(array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
// prompt the user to enter a # to search the array or Q to quit
// perform a binary search to locate the number, If found display
{
int binarySearch(int array[], int size, int value); //< -- here
}
int first = 0, // First array element
last = size - 1, // Last array element
middle, // Mid point of search
position = -1; // Position of search value
bool found = false; // Flag
while(!found && first <= last)
{
middle = (first + last) / 2; // Calculate mid point
if(array[middle] == value) // If value is found at mid
{
found = true;
position = middle;
}
else if(array[middle] > value) // If value is in lower half
last = middle - 1;
else
first = middle + 1; // If value is in upper half
}
return position;
}
// "Number %d Found at Position %d". Where the
//first %d is the number the user is searching for
// and the second %d is the location in the SORTED ARRAY.
//Else display "Number %d Not Found", where you will put the number the user is searching for in place of %d. You can use either printf() or cout.
// search continues until they hit Q since it's a loop.
|