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 = indice + 1
else
return indice

end while

return -1

2007-08-09 03:12:05 · 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 "if statement"
// 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:24:16 · answer #1 · answered by McFate 7 · 0 1

fedest.com, questions and answers