package com.example.demo;
import org.junit.Test;
import java.util.Arrays;
/**
* @Description 数组工具类Arrays的使用
* @Auther gf.x
* @Date 2020/5/16 18:58
*/
public class TestArrays {
//1. System.arraycopy()数组复制方法
@Test
public void test() {
int[] a1 = {1, 2, 3, 4, 5, 6};
int[] a2 = {11, 12, 13, 14, 15, 16};
System.arraycopy(a1, 2, a2, 3, 2);
System.out.println(Arrays.toString(a2)); //[11, 12, 13, 3, 4, 16]
}
//2. 二分法查找Arrays.binarySearch()方法
@Test
public void test1() {
int[] a = {1, 2, 323, 23, 543, 12, 59};
Arrays.sort(a); //使用二分法查找,必须先对数组进行排序
System.out.println(Arrays.toString(a)); //[1, 2, 12, 23, 59, 323, 543]
//查找某个元素是否在指定数组中,存在返回它的索引,否则返回负数
System.out.println(Arrays.binarySearch(a, 12)); //2
System.out.println(Arrays.binarySearch(a, 1112)); //-8
}
//3. 数组填充Arrays.fill(arrayname,value),
//Arrays.fill(arrayname ,starting index ,ending index ,value)
@Test
public void test2() {
int[] a = new int[6];
Arrays.fill(a, 100);
System.out.println(Arrays.toString(a)); //[100, 100, 100, 100, 100, 100]
Arrays.fill(a, 3, 6, 50);
System.out.println(Arrays.toString(a)); //[100, 100, 100, 50, 50, 50]
}
//4. 冒泡排序
@Test
public void test3() {
int[] a2 = {1, 2, 323, 23, 543, 12, 59};
bubbleSort(a2);
System.out.println(Arrays.toString(a2));
}
//冒泡排序算法实现
private void bubbleSort(int[] a2) {
int temp;
/**
* 外层遍历第一遍先找出最大的,然后遍历第二遍找出第二大的,依次...最后找出最小的
*
* 外层负责遍历取出数组中的每个元素
*/
for (int i = 0; i < a2.length; i++) {
/**
* 数组中遍历第一遍第一个元素和第二个元素比较,大的后移;
* 然后遍历第二遍第二个元素再和第三个元素比较,大的再后移...依次类推
*
* 外层遍历第一遍内层遍历 a2.length - 1 遍找出最大的元素
* 内层负责元素(遍历)比较排序
*/
for (int j = 0; j < a2.length - 1 - i; j++) {
if (a2[j] > a2[j + 1]) {
temp = a2[j];
a2[j] = a2[j + 1];
a2[j + 1] = temp;
}
}
}
}
//5. 二分法查找算法(自己实现)
@Test
public void test6() {
int[] a = {1, 2, 323, 23, 543, 12, 59};
Arrays.sort(a); //使用二分法查找,必须先对数组进行排序
System.out.println(a);
int result = dichotomySearch(a, 0, a.length, 23);
System.out.println(result);
}
//二分法查找算法实现
private int dichotomySearch(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
////////////////////////////// 其他方法 ///////////////////////////////////
//6. 判断两个数组内容是否相等 (Arrays工具类提供了这个方法)
@Test
public void test5() {
int[] a1 = {1, 2, 3, 4, 5, 6};
int[] a2 = {11, 12, 13, 14, 15, 16};
int[] a3 = {11, 12, 13, 14, 15, 16};
System.out.println(arrayEquals(a1, a2));
System.out.println(arrayEquals(a2, a3));
}
//判断两个数组内容是否相等的实现 (类似于字符串equals方法)
private boolean arrayEquals(int[] a, int[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i> << 位运算
@Test
public void test4() {
int r = 5 >> 1;
int r1 = -5 >> 1;
System.out.println(r); //2
System.out.println(r1); //-3
}
}