**
Java学习 第三章 数组(三)排序算法
**
主要内容:排序算法、排序算法横向比较、Arrays工具类的使用、数组常见异常
1.数组中涉及到的常见算法:排序算法
1.1 排序算法分类:内部排序和外部排序
1.2 十大内部排序算法
冒泡排序、快速排序:会手写
堆排序、归并排序:知道排序思想
2.冒泡排序:
实现过程:
public class BubbleSortTest {public static void main(String[] args) {int[] arr = new int[] {43,32,76,-98,0,64,33,-21,32,99};//冒泡排序for(int i = 0;i<arr.length;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.print(arr[i]+"\t");}
}
}
3.快速排序:
实现过程:
public class QuickSort {private static void swap(int[] data, int i, int j) {int temp = data[i];data[i] = data[j];data[j] = temp;}private static void subSort(int[] data, int start, int end) {if (start < end) {int base = data[start];int low = start;int high = end + 1;while (true) {while (low < end && data[++low] - base <= 0);while (high > start && data[--high] - base >= 0);if (low < high) {swap(data, low, high);} else {break;}}swap(data, start, high);subSort(data, start, high - 1);//递归调用subSort(data, high + 1, end);}}public static void quickSort(int[] data){subSort(data,0,data.length-1);}public static void main(String[] args) {int[] data = { 9, -16, 30, 23, -30, -49, 25, 21, 30 };System.out.println("排序之前:\n" + java.util.Arrays.toString(data));quickSort(data);System.out.println("排序之后:\n" + java.util.Arrays.toString(data));}
}
4.各种排序算法性能比较:
重点:冒泡排序:O(n^2)
快速排序:O(nlog2n)
5.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[]{-98,-34,2,34,54,66,79,105,210,333};int index = Arrays.binarySearch(arr3, 210); //返回下标,如果返回负数表示没找到。if(index >= 0){System.out.println(index);}else{System.out.println("未找到");}}
}
6.数组中的常见异常
1.数组角标越界的异常:ArrayIndexOutOfBoundsExcetion
2.空指针异常:NullPointerException
public class ArrayExceptionTest {public static void main(String[] args) {//1. 数组角标越界的异常:ArrayIndexOutOfBoundsExcetionint[] arr = new int[]{1,2,3,4,5};for(int i = 0;i <= arr.length;i++){System.out.println(arr[i]);}System.out.println(arr[-2]);System.out.println("hello");//2.2. 空指针异常:NullPointerException//情况一:int[] arr1 = new int[]{1,2,3};arr1 = null;System.out.println(arr1[0]);//情况二:int[][] arr2 = new int[4][];System.out.println(arr2[0][0]);//情况三:String[] arr3 = new String[]{"AA","BB","CC"};arr3[0] = null;System.out.println(arr3[0].toString());}
}