Recursive binary search in sorted array c++ -
i have write recursive function searches through sorted array.
#include <iostream> using namespace std; int find(int value, int* folge, int max) { } int main() { int const n = 7; int wert1 = 4, wert2 = 13, wert3 = 2, wert4 = 25; int folge[n] = {3,4,9,13,13,17,22}; wert1 = find(wert1, folge, n); }
this part of code given , have finish it.
know how if have 4 variables available. (min , max) have three, there way edit start point of array given next function?
the function can written following way
#include <iostream> int find( int value, int* folge, int max ) { if ( max == 0 ) return -1; int middle = max / 2; if ( folge[middle] == value ) return middle; bool lower = value < folge[middle]; int n = lower ? find( value, folge, middle ) : find( value, folge + middle + 1, max - middle - 1 ); return n != -1 && !lower ? n + middle + 1: n; } int main() { int const n = 7; int wert1 = 4, wert2 = 13, wert3 = 2, wert4 = 25; int folge[n] = {3,4,9,13,13,17,22}; std::cout << wert1 << " = " << find(wert1, folge, n) << std::endl; std::cout << wert2 << " = " << find(wert2, folge, n) << std::endl; std::cout << wert3 << " = " << find(wert3, folge, n) << std::endl; std::cout << wert4 << " = " << find(wert4, folge, n) << std::endl; return 0; }
the program output is
4 = 1 13 = 3 2 = -1 25 = -1
or 1 more test program
#include <iostream> int find( int value, int* folge, int max ) { if ( max == 0 ) return -1; int middle = max / 2; if ( folge[middle] == value ) return middle; bool lower = value < folge[middle]; int n = lower ? find( value, folge, middle ) : find( value, folge + middle + 1, max - middle - 1 ); return n != -1 && !lower ? n + middle + 1: n; } int main() { int const n = 7; int folge[n] = {3,4,9,13,13,17,22}; ( int x : { 2, 3, 4, 9, 13, 17, 22, 25 } ) { std::cout << x << " -> " << find( x , folge, n ) << std::endl; } return 0; }
its output is
2 -> -1 3 -> 0 4 -> 1 9 -> 2 13 -> 3 17 -> 5 22 -> 6 25 -> -1
Comments
Post a Comment