• 周四. 10 月 3rd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Recursive and non recursive binary search in Java

King Wang

1 月 3, 2022

Non recursive implementation of binary search

/**
* Non recursive search key
* @param array
* @param key
* @return
*/
public static int binarySearch(int[] array, int key) {

bubbleSort(array);
int left = 0;
int right = array.length - 1;
int mid;
while (left <= right) {

mid = (left + right) / 2;
if (array[mid] == key) {

return mid + 1;
} else if (array[mid] < key) {

left = mid + 1;
} else {

right = mid - 1;
}
}
return -1;
}

Recursive implementation of binary search

/**
* Recursive search key
*
* @param array
* @param key
* @param left
* @param right
* @return
*/
public static int sort(int[] array, int key, int left, int right) {

if (left <= right) {

int mid = left + right;
if (key == array[mid]) {

return mid + 1;
} else if (key < array[mid]) {

return sort(array, key, left, mid - 1);
} else {

return sort(array, key, mid + 1, right);
}
}
return -1;
}

Query the location of the first occurrence element

/**
* Query where the first element appears
*
* @param array
* @param key
* @return
*/
public static int biSearchFirst(int[] array, int key) {

int len = array.length;
int left = 0;
int right = len - 1;
int mid = 0;
while (left < right) {

mid = (left + right) >> 1;
if (array[mid] < key) {

left = mid + 1;
} else {

right = mid;
}
}
if (array[left] != key) {

return -1;
} else {

return left;
}
}

Query the location of the last occurrence element

/**
* Query the location of the last occurrence of the element
*
* @param array
* @param key
* @return
*/
public static int biSearchLast(int[] array, int key) {

int len = array.length;
int left = 0;
int right = len - 1;
int mid = 0;
while (left < right) {

mid = (left + right + 1) >> 1;
if (array[mid] <= key) {

left = mid;
} else {

right = mid - 1;
}
}
if (array[left] != key) {

return -1;
} else {

return right;
}
}

发表回复