Wyszukaj posortowaną tablicę C

// Search sorted array of integers "arr" of lenght "arr_len" for value "key"
// Return index of "key" if "key" is found, else return -1

int search_sorted_array(int arr[], int arr_len, int key) {

    int low = 0, high = arr_len - 1;
    int middle;

    if (arr_len < 1) return -1; // If array is empty return -1

    while ( high >= low ) {

        middle = (low + high) / 2 ;	// Get the middle of the array

        if ( arr[middle] == key ) return middle; // Return index of found key

        else if ( arr[middle] > key ) high = middle - 1;

        else low = middle + 1;

    }
	
  	// Key not in array, return -1
    return -1;
}
Filip Výrostko