数组的搜索:从一个数组中搜索指定元素的索引位置;
搜索的方式:
(1)线性搜索:从头到位 / 从尾到头(indexOf / lastIndexOf)
但是这种搜索方式对于元素个数多的数组性能极低(最少搜索次数为1,最多搜索次数为N,平均搜索次数 (N+1) / 2)。
(2) 二分搜索法(折半查找法/二分搜索法):
// 线性搜索
import java.util.ArrayList;
import java.util.List;
public class LinearSearch{
public static void main(String args[]){
int[] nums = new int[]{6,1,3,3,5,6,9,1};
int ele = 1;
List<Integer> list = linearSearch(nums,ele);
for(int index : list){
System.out.println(index);
}
}
// 线性搜索
public static List<Integer> linearSearch(int[] nums, int ele){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0 ; i < nums.length; i++){
if (nums[i] == ele){
list.add(i);
}
}
return list;
}
}
// 二分查找法的前提:数组必须是有序的!
class BinarySearch
{
public static void main(String[] args)
{
int[] nums = new int[]{4,3,2,5,1,99,22,23,11,21,8,6,9,18,919};
selectSort(nums);
printArray(nums);
int index = binarySearch(nums,99);
if (index == -1) // 判断元素是否存在
{
System.out.println("This element does not exist! ");
}else{
System.out.println(index);
}
}
// 二分查找法
public static int binarySearch(int[] nums, int ele){
int lowIndex = 0;
int highIndex = nums.length-1;
while(lowIndex <= highIndex){
int midIndex = (lowIndex + highIndex) / 2;
if ( ele < nums[midIndex])
{
highIndex = midIndex - 1;
}
else if(ele > nums[midIndex])
{
lowIndex = midIndex + 1;
}
else
{
return midIndex;
}
}
return -1;
}
// 选择排序
public static void selectSort(int[] nums){
for (int i = 0; i < nums.length-1 ; i++)
{
int minValueIndex = i;
for(int j = 0; j < nums.length-1-i; j++){
if (nums[minValueIndex] > nums[i+j+1])
{
minValueIndex = i+j+1;
}
}
int temp = nums[i];
nums[i] = nums[minValueIndex];
nums[minValueIndex] = temp;
}
}
// 打印数组
public static void printArray(int[] nums){
String res = "[";
for (int i = 0; i < nums.length; i++){
res = res + nums[i];
if ( i != nums.length - 1){
res = res + ",";
}
}
res = res + "]";
System.out.println(res);
}
}