数组操作工具,专门操作数组元素;
/**
* 返回数组内容toString(数组)
* 排序Arrays.sort();
* 二分搜索:Arrays.binarySearch(arr, 55);
*/
public class ArraysDemo01 {
public static void main(String[] args) {
int[] arr = {10,5,66,34,55,88};
//[I@1b6d3586
System.out.println(arr);
//返回数组内容toString(数组)
//[10, 5, 66, 34, 55, 88]
System.out.println(Arrays.toString(arr));
//排序API,默认数组升序
Arrays.sort(arr);
//[5, 10, 34, 55, 66, 88]
System.out.println(Arrays.toString(arr));
//二分搜素技术,(前提是排序完成,否则bug)
int i = Arrays.binarySearch(arr, 55);
//3
System.out.println(i);
//-7; 数组中找不到该元素 - (应当插入索引位+1)
System.out.println(Arrays.binarySearch(arr, 555));
}
}
/**
* Comparator比较器
*/
public class ArraysDemo02 {
public static void main(String[] args) {
Integer[] arr = {10,5,66,34,55,88};
//[10, 5, 66, 34, 55, 88]
System.out.println(Arrays.toString(arr));
//自定义比较器对象,只能用引用类型;
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
//return o1-o2;//默认升序
return o2-o1;//降序
}
});
System.out.println(Arrays.toString(arr));
System.out.println("==========排序学生信息============");
Student[] students = new Student[3];
students[0] = new Student("a",20,173.3);
students[1] = new Student("b",19,163.4);
students[2] = new Student("c",24,163.3);
Arrays.sort(students, new Comparator() {
@Override
public int compare(Student o1, Student o2) {
//return o1.getAge() - o2.getAge();//根据年龄正序排列
return Double.compare(o1.getHeight(), o2.getHeight());//根据身高正排,专门处理浮点型
}
});
System.out.println(Arrays.toString(students));
}
}
每轮选择当前位置,找后面比他小的交换位置;
第一轮先找出最小的放在开始,与冒泡相反(找最大)
选择轮次:数组长度-1;
控制每轮开始位置,与后面元素选择次数;
/**
* 选择排序
*/
public class Test {
public static void main(String[] args) {
int[] arr = {10,5,66,34,55,88};
//选择排序;a[i]锁定每次循环开始位置
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j < arr.length ; j++) {
if (arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
//冒泡排序
int[] arr2 = {10,5,66,34,55,88};
for (int i = 0; i < arr2.length-1; i++) {
//j < arr2.length - i - 1;每次循环排出最大值后,下一次排序-1
for (int j = 0; j < arr2.length - i - 1; j++) {
if (arr2[j]>arr2[j+1]){
int temp = arr2[j];
arr2[j] = arr2[j+1];
arr2[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(arr2));
}
}
二分查找查询性能好,但前提是必须排好序;
找数组中间位置值和变量比较;
大,向右+1,和最后位取中间位置比较;
小,向左-1和最初位取中间位置比较,
重复直到查到
最大最小索引相等,还没找到,失败;
/**
* 二分查找,效率高
*/
public class Test02 {
public static void main(String[] args) {
int[] arr = {5, 10, 34, 55, 66, 88,98,99};
System.out.println(binarySearch(arr,99));
System.out.println(binarySearch(arr,34));
System.out.println(binarySearch(arr,35));
}
public static int binarySearch(int[] arr,int data){
//定义左右起始索引
int left = 0;
int right = arr.length-1;
while (left <= right){
int middleIndex = (left + right)/2;
if (data > arr[middleIndex]){
left = middleIndex+1;
}else if (data < arr[middleIndex]){
right = middleIndex-1;
}else {
return middleIndex;
}
}
return -1;
}
}