Sei sulla pagina 1di 3

9/22/13

CAPE Computer Science Unit 2 - LiveBinder

A fast way to search a sorted array is to use abinary search. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half.

Pseudocode: BinarySearch(array, size, key) BEGIN low = 0 high = size while (low + 1 < high) test = (low + high)/2 if (array[test] > key) high = test else low = test endwhile if (array[low] = = key return low else
www.livebinders.com/play/play?id=127326 1/3

9/22/13

CAPE Computer Science Unit 2 - LiveBinder

return -1 END

C Program: 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 . 2 1 . 2 2 . 2 3 . 2 4 . 2 5 . 2 6 . 2 7 . 2 8 .
# i n c l u d e < s t d i o . h > # i n c l u d e < c o n i o . h > v o i dm a i n ( ) { i n ta [ 1 0 ] , n , i ; i n tl o w , h i g h , m i d , k e y ; c l r s c r ( ) ; p r i n t f ( e n t e rt h et o t a ln u m b e r s : " ) ; s c a n f ( % d " , & n ) ; p r i n t f ( e n t e rt h ea r r a ye l e m e n t si na s c e n d i n go rd e s c e n d i n go r d e r : ") ; f o r ( i = 0 ; i < n ; i + + ) s c a n f ( % d " , & a [ i ] ) ; l o w = 0 ; h i g h = 9 ; m i d = ( l o w + h i g h ) / 2 ; p r i n t f ( \ n e n t e rt h en u m b e rt ob es e a r c h e d : " ) ; s c a n f ( % d " , & k e y ) ; w h i l e ( l o w < = h i g h& &a [ m i d ] ! = k e y ) { i f ( k e y < a [ m i d ] ) h i g h = m i d 1 ; e l s e l o w = m i d + 1 ; m i d = ( l o w + h i g h ) / 2 ; } I f ( a [ m i d ] = = k e y ) {
2/3

www.livebinders.com/play/play?id=127326

9/22/13

CAPE Computer Science Unit 2 - LiveBinder

2 9 . 3 0 . 3 1 . 3 2 . 3 3 . 3 4 . 3 5 . 3 6 .

p r i n t f ( \ n t h en u m b e ri sf o u n da tp o s i t i o n" , m i d ) ; } e l s e { p r i n t f ( \ n t h en u m b e ri sn o tf o u n d " ) ; } g e t c h ( ) ; }

www.livebinders.com/play/play?id=127326

3/3

Potrebbero piacerti anche