1、已经排序的数组,查找索引最小的值:
int binary_search(int[] array, int n, int value) { int maxIndex = n; int minIndex = 1; int index; while (maxIndex >= minIndex) { index = (maxIndex + minIndex) / 2; if (array[index - 1] == value) { while (--index > 0) { if (array[index - 1] == value) continue; break; } return index; } if (array[index - 1] > value) { maxIndex = index - 1; continue; } if (array[index - 1] < value) { minIndex = index + 1; continue; } } return -1; }
调用方法:
int index = binary_search(new[] { 1 }, 1, 1); index = binary_search(new[] { 1 }, 1, 2); index = binary_search(new[] { 1, 2 }, 2, 2); index = binary_search(new[] { 1, 2 }, 2, 1); index = binary_search(new[] { 1, 2 }, 2, 3); index = binary_search(new[] { 1, 2, 3 }, 3, 2); index = binary_search(new[] { 1, 2, 3 }, 3, 3); index = binary_search(new[] { 1, 2, 3 }, 3, 1); index = binary_search(new[] { 1, 2, 3 }, 3, 4); index = binary_search(new[] { 1, 2, 3, 3, 3, 3, 3, 4 }, 8, 3); index = binary_search(new[] { 1, 2, 3, 4 }, 4, 4); index = binary_search(new[] { 1, 2, 3, 4 }, 4, 2); index = binary_search(new[] { 1, 2, 3, 4 }, 4, 1); index = binary_search(new[] { 1, 2, 3, 4 }, 4, 5);