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
|
#include <iostream>
// return position of value if found in [left,right], return -1 otherwise
int find( const int ordered_list[], int left, int right, int value )
{
if( right < left ) return -1 ;
const int mid = left + (right-left)/2 ;
if( ordered_list[mid] == value ) return mid ;
else return ordered_list[mid] > value ? find( ordered_list, left, mid-1, value )
: find( ordered_list, mid+1, right, value ) ;
}
// return position of value if found in ordered_list, return -1 otherwise
int find( const int ordered_list[], int size, int value )
{ return find( ordered_list, 0, size-1, value ) ; }
// erase element at position pos
void erase_at( int ordered_list[], int size, int pos )
{
for( int i = pos+1 ; i < size ; ++i ) ordered_list[i-1] = ordered_list[i] ;
}
// erase first element equal to value, return true.
// return false if no element equal to value was found
bool erase( int ordered_list[], int size, int value )
{
const int pos = find( ordered_list, size, value ) ;
if( pos == -1 ) return false ;
erase_at( ordered_list, size, pos ) ;
return true ;
}
void print( const int list[], int size )
{
for( int i = 0 ; i < size ; ++i ) std::cout << list[i] << ' ' ;
std::cout << '\n' ;
}
int main()
{
const int N = 20 ;
int ordered_list[N] ;
for( int i = 0 ; i < N ; ++i ) ordered_list[i] = i+1 ;
print( ordered_list, N ) ;
int curr_size = N ;
while( curr_size > 0 )
{
int value ;
std::cout << "value? " && std::cin >> value ;
if( erase( ordered_list, curr_size, value ) ) --curr_size ;
print( ordered_list, curr_size ) ;
}
}
|