线性查找
代码如下:
package ClassDemo;
import java.util.Arrays;
public class TestLinearSearch {
public static void main(String[] args) {
int[] list = {1,7,2,3,4,5,6,8,9,10};
// int i = linearSearch(list, 1);
// int i = binarySearch(list, 9);
// System.out.println(i);
System.out.println(Arrays.toString(list));
// arraySelectionSort(list);
arrayInsertionSort(list);
System.out.println(Arrays.toString(list));
}
private static void arrayInsertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
//保存当前元素
int currentElement = list[i];
int k;
for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {
list[k + 1] = list[k];
}
list[k + 1] = currentElement;
}
}
/**
* 选择排序数组list
* @param list
* @return
*/
private static void arraySelectionSort(int[] list) {
for (int i = 0; i < list.length; i++) {
int currentMin = list[i];
int currentMinIndex = i;
//找到最小的元素currentMin,currentMinIndex
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//将最小的元素list[currentMinIndex]和list[i]互换
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
/**
* 线性查找数组list中值为key的元素,返回该元素的下标i, 如果找不到返回-1
* @param list 需要查找的数组
* @param key 需要查找的元素
* @return i 返回的下标
*/
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i ++) {
if (key == list[i]) {
return i;
}
}
return -1;
}
/**
* 二分查找数组list中值为key的元素,返回该元素的下标i, 如果找不到返回-1
* @param list 需要查找的数组
* @param key 需要查找的元素
* @return i 返回的下标
*/
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid]) {
high = mid -1;
} else if (key == list[mid]) {
return mid;
} else {
low = mid + 1;
}
}
return -1;
}
}