#include <iostream> #include <string> #include <fstream> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; int searchList(int asciiA[], int, int); int binarySearch(int asciiA[], int, int); void selectionSort(int [], int); int main() { int characters; int choice; char numElems; string line = "==================================================================="; bool quit = false; char asciiA[10000]; while (!quit) { cout << "How many characters do you want? (Choose from 1-10000): "; cin >> characters; cout << "(1.) Print Array" << endl; cout << "(2.) Perform Linear Search" << endl; cout << "(3.) Sort Array" << endl; cout << "(4.) Perform Binary Search" << endl; cout << "(5.) Quit" << endl; cout << "Select an option from the above: "; cin >> choice; cout << line << endl; switch (choice) { case 1: for (int i=0; i<characters; ++i) { asciiA[i] = rand() % 256; cout << char(asciiA[i]); }; cout << "\n"; cout << line << endl; case 2: cout << "What Character are you looking to find?: "; cin >> numElems; case 3: case 4: case 5: cout << "Goodbye. . . . . hahahahahaha" << endl; quit = true; default:cout << "PLEASE TRY AGAIN ^_^\n" ; } } return 0; } // Linear search function int searchList(int asciiA[], int numElems, int value) { int index = 0; int position = -1; bool found = false; while (index < numElems && !found) { if (asciiA[index] == value) // if the value is found { found = true; // set flag position = index; // Record the value's subscript } index++; // Go to the next element //cout << "What is the Number of iteration: " << index << endl; } return position; // Return the positon , or -1 } // Binary search function int binarySearch(int asciiA[], int size, int value) { int first = 0, last = size - 1, middle, position = -1; bool found = false; while (!found && first <= last) { middle = (first + last) / 2; if (asciiA[middle] == value) { found = true; position = middle; } else if (asciiA[middle] > value) last = middle - 1; else first = middle + 1; } return position; } // Selection Sort function void selectionSort(int asciiA[], int size) { int startScan, minIndex, minValue; for (startScan = 0; startScan < (size - 1); startScan++) { minIndex = startScan; minValue = asciiA[startScan]; for(int index = startScan + 1; index < size; index++) { if (asciiA[index] < minValue) { minValue = asciiA[index]; minIndex = index; } } asciiA[minIndex] = asciiA[startScan]; asciiA[startScan] = minValue; } }
In this program, I am having difficulty sorting the array using the selection sort method,
Using linear and binary search on the sorted array to find the element entered by the user,
Computing needed number of iterations for both linear and binary searches and displaying them.
NOTE: I had to do the menu option so the user can select an option to perform.