If it's any consolation.. here is the entire program... as you can see, my method of terminating the sort sequence would work in this program.
Code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
system("cls");
int array[11] = {90, 1, 43, 16, 32, 12, 6, 14, 96, 20, 3};
cout << "\nHere is the unsorted array: \n\n";
for(int i = 0; i < 11; i++)
{
cout << " " << array[i] << " ";
}
cout << endl << endl;
system("pause");
//Bubble Sort Algorithm
for(int p = 0; p < 10; p++) //The outter FOR loop will execute the
{ //bubble sort "array capacity - 1" times.
int place_holder = 0;
for(int i = 0; i < 10; i++) //The inner FOR loop executes an
{ //"element by element" comparison
int j = i;
if(array[i] > array[++j]) //The "swap" algorithm will "push"
{ //larger numbers to the greater
place_holder = array[j]; //end of the array
array[j] = array[i];
array[i] = place_holder;
}
}
if(place_holder == 0) //A switch is provided to "break" the
//FOR loop if no swaps are being made.
break;
}
cout << "\n\nHere is the sorted array: \n\n";
for(int i = 0; i < 11; i++)
{
cout << " " << array[i] << " ";
}
cout << endl << endl;
system("pause");
int search_key = 0;
cout << "\n\nEnter an integer type search key: ";
cin >> search_key;
//Binary Search
int low = 0;
int high = 10;
int middle = 0;
while( low <= high )
{
middle = ( low + high ) / 2;
if( search_key == array[middle] ) //match
{
cout << "\nYour search key '" << search_key << "' was found in array element ["
<< middle << "]\n\n"
<< "\nThank you for viewing my sort and search demonstration.";
exit(0);
}
else if( search_key < array[middle] )
high = middle - 1; //search low end of array
else
low = middle + 1; //search high end of array
}
cout << "\nYour search key << search_key << is not part of the array.\n\n"
<< "Better luck next time.";
return EXIT_SUCCESS;
}
I think my previous example may have been to ambiguous. If array[] was restricted to a non-zero domain would work.