方法1:Arrays.sort(T[] arr);
方法2:
冒泡排序(从数组末端位置开始排最大值或最小值);
方法3:选择排序(从数组起始位置开始排最大值或最小值)。
class="java" name="code">
public class TestSortArray {
private static int[] arr01 = new int[]{12, 24, 4, 35, 7, 26};
public static void main(String[] args) {
int[] arr02 = arr01.clone();
int[] arr03 = arr01.clone();
sortArray(arr01);
System.out.println("====================================");
bubbleSortArray(arr02);
System.out.println("====================================");
selectSortArray(arr03);
}
private static void sortArray(int[] arr) {
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
// 冒泡排序,从小到大
private static void bubbleSortArray(int[] arr) {
int temp;
for (int i = 1; i < arr.length; i++) {
for (int k = 0; k < arr.length - 1; k++) {
if (arr[k] > arr[k + 1]) {
temp = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
System.out.println(Arrays.toString(arr));
}
// 选择排序,从小到大
private static void selectSortArray(int[] arr) {
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int k = i + 1; k < arr.length; k++) {
if (arr[i] > arr[k]) {
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
System.out.println(Arrays.toString(arr));
}
}
执行结果如下:
引用
[4, 7, 12, 24, 26, 35]
====================================
[12, 4, 24, 7, 26, 35]
[4, 12, 7, 24, 26, 35]
[4, 7, 12, 24, 26, 35]
[4, 7, 12, 24, 26, 35]
[4, 7, 12, 24, 26, 35]
[4, 7, 12, 24, 26, 35]
====================================
[4, 24, 12, 35, 7, 26]
[4, 7, 24, 35, 12, 26]
[4, 7, 12, 35, 24, 26]
[4, 7, 12, 24, 35, 26]
[4, 7, 12, 24, 26, 35]
[4, 7, 12, 24, 26, 35]