Как найти позицию (индекс массива ) числа в данном массиве?
I have to find the position (array index) of a number in an array, the number can lie in between any other two numbers in the array. I have written code for this but I want some alternative way to do this. example: let the array be given as float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; Now I have to find the position of 12.6 in the given array, since 12.6 lies between 10.6 and 17.5 in the above array so, it should return array index as 4. Is there any other way to do this? I know it can be done by using binary search but I don't know how to implement it (since the number is not present in array) The array is sorted (ascending order)
Что я уже пробовал:
#include<stdio.h> int main() { int position; int i; float num=12.6; // position of this number has to be determined i.e. it lies between 10.6 // and 17.5 in the array given below so it should give array index as 4 float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; // any random array for(i=0;i<10;i++) { if(arr[i] > num) { position=i-1; break; } } printf("array index is %d",position); // this gives index as 4 return 0; }
KarstenK
Важным моментом является то, что Ваш массив отсортирован. Когда это ясно, то бинарный поиск-это правильный способ решения задачи!!!