English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Algorithm:
-------------

start <- 0
end <- a.length -1

while start <= end

if (end-start) is multipliable by 2?
index<-start + (end-start)/2
else
index <-start +(end-start+1)/2


if a[index]>n
end <-index-1
else if(a[index] start <- index + 1
else
return index

end while

return -1

2007-08-09 02:59:33 · 1 answers · asked by Anonymous in Computers & Internet Programming & Design

1 answers

int start = 0;
int end = a.length - 1;
while (start <= end) {
if (((end - start) % 2) == 0)
index = start + (end - start) / 2;
else
index = start + (end - start + 1) / 2;

// Note that the above could just be:
// index = start + (end - start + 1) / 2;
// in all cases, since if end-start is even
// the +1 will be truncated in the integer
// division operation

if (a[index] > n) end = index - 1;
else if (a[index] < n) start = index + 1;
else return index;
}

return -1;

2007-08-09 03:27:18 · answer #1 · answered by McFate 7 · 1 0

fedest.com, questions and answers