线性查找
public class ArrayTest2 {
public static void main(String[] args){
String[] arr = new String[]{"hh","zs","dd","dv","de","ce"};
//1.方法一:
for(int i = 0;i < arr.length / 2;i++){
String temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
//方法二:
for(int i = 0,j = arr.length - 1;i < j;i++,j--){
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for(int i = 0;i < arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
String dest = "dv";
boolean isFlag = true;
for(int i = 0;i<arr.length;i++){
if(dest.equals(arr[i])){
System.out.println("找到了指定的元素位置为:" + i);
isFlag = false;
break;
}
}
if(isFlag){
System.out.println("很遗憾,没有找到哦");
}
}
}
二分法查找
//二分法查找
//前提:所要查找的数组必须有序
public class ArrayTest2 {
public static void main(String[] args){
int[] arr2 = new int[]{-20,-10,-5,-4,-3,1,2,3};
int dest1 = -10;
int head = 0;
int end = arr2.length-1;
boolean isFlag1 = true;
while(head<=end){
int middle = (head + end) / 2;
if(dest1 == arr2[middle]){
System.out.println("找到了指定元素,位置为:" + middle);
isFlag1 = false;
break;
}else if(arr2[middle] > dest1){
end = middle - 1;
}else{
head = middle + 1;
}
}
if(isFlag1){
System.out.println("很遗憾,没有找到啦!");
}
}
}
}
冒泡排序
public class BubbleSortTest {
public static void main(String[] args){
int[] arr = new int[]{23,37,42,424,44,5566,76,21,24};
//冒泡排序
for(int i = 0;i < arr.length - 1;i++){
for(int j = 0;j < arr.length - 1 - i;j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i] + "\t");
}
}
}
java.util.Arrays的常见调用
import java.util.Arrays;
/*
* java.util.Arrays:操作数组的工具类,里面定义了很多操作数组的方法
*
*
*/
public class ArraysTest {
public static void main(String[] args){
//1.boolean equals(int[] a,int[] b):判断两个数组是否相等
int arr1[] = new int[]{1,2,3,4};
int arr2[] = new int[]{1,3,2,4};
boolean isEquals = Arrays.equals(arr1, arr2);
System.out.println(isEquals);
//2.String toString(int[] a):输出数组信息
System.out.println(Arrays.toString(arr1));
//3.void fill(int[] a,int val):将指定值填充到数组之中
Arrays.fill(arr1, 10);
System.out.println(Arrays.toString(arr1));
//4.void sort(int[] a):对数组进行排序
Arrays.sort(arr2);
System.out.println(Arrays.toString(arr2));
//5.int binarySearch(int[] a, int key);
int[] arr3 = new int[]{2,3,5,7,11,13,17,19};
int index = Arrays.binarySearch(arr3, 7);
if(index >= 0){
System.out.println(index);
}else{
System.out.println("未找到");
}
}
}