//Tool: Dev C++
//notes: first, bubble sort
// second, binary search
#include <iostream>
void bin_search( int array[], int low, int high, int key );
void bubble_sort( int array[], int len );
int main( void )
{
int array[]= { 4, 6, 22, 66, 43, 23, 90, 65, 42 };
int key;
int low;
int high;
key= 90;
high= sizeof( array )/ sizeof( array[ 0 ] );
low= 0;
bubble_sort( array, high );
bin_search( array, low, high- 1, key );
std::cout<< std::endl;
return 0;
}
void bin_search( int array[], int low, int high, int key )
{
int mid;
mid= ( low+ high )/ 2;
if( low> high )
{
return ; //game over
}
if( array[ mid ]== key )
{
std::cout<< "I find: key= "<< array[ mid ];
}
else if( array[ mid ]> key )
{
bin_search( array, low, mid- 1, key );
}
else
{
bin_search( array, mid+ 1, high, key );
}
return ;
}
void bubble_sort( int array[], int len )
{
int temp;
for( int i= 0; i< len- 1; i++ )
{
for( int j= 0; j< len- 1- i ; j++ )
{
if( array[ j ]> array[ j+ 1 ] )
{
temp= array[ j ];
array[ j ]= array[ j+1];
array[ j+ 1 ]= temp;
}
}
for( int k= 0; k< len; k++ )
{
std::cout<< array[ k ]<< " ";
}
std::cout<< "\n";
}
}
The result:
4 6 22 43 23 66 65 42 90
4 6 22 23 43 65 42 66 90
4 6 22 23 43 42 65 66 90
4 6 22 23 42 43 65 66 90
4 6 22 23 42 43 65 66 90
4 6 22 23 42 43 65 66 90
4 6 22 23 42 43 65 66 90
4 6 22 23 42 43 65 66 90
I find: key= 90
0 Comment:
Post a Comment