1. 线性搜索
理论解释引自此处。
Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
线性搜索:最简单的搜索策略,顺序遍历数组元素,如果找到目标元素则退出。
package com.fqyuan.search;
import java.util.Random;
import org.junit.Test;
public class LinearSearch {
public static int linearch(int[] arr, int target) {
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (target == arr[i]) {
index = i;
break;
}
}
return index;
}
@Test
public void test() {
int[] arr = new int[100];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(arr.length);
SearchUtils.printArr(arr);
if (linearch(arr, 50) != -1)
System.out.println("Found 50 at: " + linearch(arr, 50));
else
System.out.println("Not found.");
}
}
2. 二分搜索
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.
二分搜索的要求及思想:二分搜索是采取divide and conquer分而治之思想,时间复杂度为(Ologn)的算法,在进行搜索之前,必须保证待搜索的的数组是有序的。
package com.fqyuan.search;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
public class BinarySearch {
public static int binarySearchNonRec(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
int mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (target < arr[mid])
high = mid - 1;
else {
low = mid + 1;
}
}
return -1;
}
public static int binarySearchRec(int[] arr, int target) {
return binarySearchRec(arr, target, 0, arr.length - 1);
}
private static int binarySearchRec(int[] arr, int target, int low, int high) {
if (low > high)
return -1;
int mid = low + (high - lo