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
|
#include <iostream>
#include <stdlib.h>
using namespace std;
char **Create2DArray (unsigned int NumRows, unsigned int NumCols)
{
char ** TwoDArray;
TwoDArray = new char * [NumRows];
for (unsigned int i = 0; i < NumRows; i++)
TwoDArray [i] = new char [NumCols];
return TwoDArray;
}
void Free2DArray (char **TwoDArray, unsigned int NumCols)
{
for (unsigned int i = 0; i < NumCols; i++)
delete [] TwoDArray [i];
delete [] TwoDArray;
}
void BubbleSort (char ** Array, char NumofNames = 20)
{
char i=0, j=0;
for (i = 0; i < NumofNames; i++) //states i, must be less than allocated amount
{
for (j = 0; j < NumofNames-1; j++) //???
{
if (strcmp (Array [j+1], Array [j]) == -1) //checks to see if i is greater than j in array
{
char *temp = Array [j]; //creates a temporary location for i
Array [j] = Array [j+1]; //swaps i with j
Array [j+1] = temp; //places j at top of array
}
}
}
}
char BinarySearch (char TwoDArray[10], char first, char last, char C)
{
do {
char mid = (last + first) / 2; // compute mid point.
if (TwoDArray[mid] == C)
return mid;
first = mid + 1; // repeat search in top half.
else if (C < TwoDArray[mid])
last = mid - 1; // repeat search in bottom half.
else
first = mid+1; // found it. return position /////
} while (first <= last);
return -1;
}
int main ()
{
unsigned int NumofNames = 5;
unsigned int NumCols = 20;
cout << "Enter your names with a space in between each name. Type the ENTER key when finished. " << endl;
cout << "\nEnter list of names: ";
char ** TwoDArray = Create2DArray (NumofNames, NumCols);
for (unsigned int i = 0; i < NumofNames; i++)
{
cin >> TwoDArray [i];
if ((cin.get() == '\n') && (NumofNames <= 5))
{
cout << "\nYou have entered: " << endl;
for (unsigned int j = 0; j < NumofNames; j++)
cout << TwoDArray [j] << " " << endl;
cout << endl;
}
}
BubbleSort (TwoDArray, NumofNames);
cout << "\nHere are the names in sorted order:\n";
for (unsigned int k = 0; k < NumofNames; k++)
{
cout << TwoDArray [k] << " " << endl;
}
Free2DArray (TwoDArray, NumCols);
cout << "Which name do you want to search for? " << endl;
for (unsigned int i = 0; i < NumofNames; i++)
{
cin >> TwoDArray [i];
BinarySearch (TwoDArray, char first, char last, char C);
cout << "The index of the string is: " << TwoDArray << endl;
}
return 0;
}
| |