int firstPosition(int x, int [] a) {
int lower = 0;
int upper = a.length;
while (lower != upper) {
int mid = (lower + upper)/2;
**if (x <= a[mid]) {** // the line I don't understand
upper = mid;
} else {
lower = mid + 1;
}
return (lower);
}
如果a = {4,4,5,6,7,8,9,9,9}算法會返回以下選擇x?Java首先定位算法
I)中X = 3
ⅱ)X = 4
ⅲ)X = 5
IV),X = 9
V)X = 11
我嘗試過這個程序,例如x = 3,a.length返回10,所以upper總是等於10.
while (3 ! = 0) { // execute line
int mid = lower + upper/2 - which is (0 + 10)/2 = 5
if (x <= a[mid]) // I assume that means if 3 is less than or equal to 5? 5 then replace mid with 5 and then...
lower = mid + 1 // 5+1 = 6, return 6 as lower?
它看起來像二進制搜索。如果數組的中間元素更大,則降低中間值。 – 2011-05-27 19:15:09