目录
一、冒泡排序
实现:
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 - 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.print(arr[i] + "\t");
}
System.out.println();
}
//结果
//-98 -21 0 32 32 33 43 64 76 99
二、快速排序
实现:
public class TestProject {
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
public 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("排序前:" + java.util.Arrays.toString(data));
quickSort(data);
System.out.println("排序后:" + java.util.Arrays.toString(data));
}
}
/*
排序前:[9, -16, 30, 23, -30, -49, 25, 21, 30]
排序后:[-49, -30, -16, 9, 21, 23, 25, 30, 30]
*/
三、Arrays工具类
四、数组使用中的常见异常
>数组角标越界的异常:ArrayIndexOutOfBoundsException
>空指针异常:NullPointerException
(一旦出现异常,未处理时,就终止执行)