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
|
#include <iostream>
#include <string>
using namespace std;
const int SIZE = 10;
// quickSort() uses the quicksort algorithm to sort array
// set, from set[beg] through set[end]
template <class T>
void quickSort(T set[], int beg, int end);
// partition selects first value in the set as the pivot; set is
// arranged so that all values less than the pivot are on its
// left and all the values greater than pivot are on its right
template <class T>
int partition(T set[], int beg, int end);
const int cnt = 10;
template <class T>
void quickSort(T set[], int beg, int end)
{
int piv;
if (beg < end) {
piv = partition(set, beg, end); // get pivot point
quickSort(set, beg, piv - 1); // sort first sublist
quickSort(set, piv + 1, end); // sort second sublist
} // endif
} // end quickSort()
template <class T>
int partition(T set[], int beg, int end)
{
int pivNdx = beg; // beginning index for pivot index
int pivot = set[beg]; // assign pivot value
for (int k = beg + 1; k <= end; k++) {
if (set[k] < pivot) {
pivNdx++;
swap(set[pivNdx], set[k]);
} // endif
} // endfor
swap(set[beg], set[pivNdx]);
return pivNdx; // return pivot index
} // end partition()
template <class T>
bool isMember(T [] , int , int, T val);
template <class T>
bool isMember(T ary[] , int first ,int last , T val)
{
int middle;
middle = (first + last) /2;
if(first > last)
return false;
if(ary[middle] == val)
return middle;
if(ary[middle]<val)
return isMember(ary, middle+1,last, val);
else
return
isMember(ary, first,middle-1, val);
}//end isMember
int main()
{
string sarray[SIZE] = {"Steve" , "John" , "Allen" , "Fred" , "Lonnie" , "Kim" , "Jennifer" , "Josh" , "Morgan" , "Mike" } ;
int iarray[SIZE] = { 1, 3, 65, 44, 33, 45, 98, 87, 101, 31};
int searchitmint;
string searchitmstr;
quickSort(sarray, 0, SIZE - 1); //sort the string array
cout << "Enter a number to search for in the array: " ;
cin >> searchitmint;
cout << endl << endl;
cout << "Enter a string to search for in the array: " ;
cin >> searchitmstr;
bool resultsint;
bool resultsstr;
resultsint = isMember(iarray, 0, SIZE-1 , searchitmint);
resultsstr = isMember(sarray, 0, SIZE-1 , searchitmstr);
if(resultsint == false)
cout << "That number does not exist in the array! " << endl;
else
{
cout << "The number " << searchitmint << " is found in the array! " << endl << endl;
}
if(resultsstr == false)
cout << "That string does not exist in the array! " << endl;
else
{
cout << "The string " << searchitmstr << " is found in the array! " << endl << endl;
}
return 0;
}//endmain
|