数组排序方法
整合几种数组排序的方法
首先创建随机数组
public static int[] getArr() {
int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = (int)(Math.random()*100);
}
return arr;
}
一、Arrays.sort(arr)
public static void main(String[] args) {
int[] list = getArr();
System.out.println(Arrays.toString(list));
Arrays.sort(list);
System.out.println(Arrays.toString(list));
}
[42, 24, 42, 91, 78, 58, 93, 95, 15, 30]
[15, 24, 30, 42, 42, 58, 78, 91, 93, 95]
二、冒泡法排序
public static void MPSort(int[] arr) {
int k = 0;
while (true){
int j = 0;
for (int i=0; i<arr.length-1-k; i++) {
if (arr[i]>arr[i+1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
j++;
}
}
k++;
if (j==0) break;
}
}
public static void main(String[] args) {
int[] list0 = getArr();
System.out.println(Arrays.toString(list0));
MPSort(list0);
System.out.println(Arrays.toString(list0));
}
[19, 52, 69, 24, 86, 79, 64, 31, 93, 12]
[12, 19, 24, 31, 52, 64, 69, 79, 86, 93]
三、选择法排序
public static void SLTSort(int[] list) {
for (int i = 0; i < list.length; i++) {
int Min = list[i];
int MinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (Min > list[j]) {
Min = list[j];
MinIndex = j;
}
}
if (MinIndex != i) {
list[MinIndex] = list[i];
list[i] = Min;
}
}
}
public static void main(String[] args) {
int[] list1 = getArr();
System.out.println(Arrays.toString(list1));
SLTSort(list1);
System.out.println(Arrays.toString(list1));
}
[75, 13, 40, 91, 91, 99, 71, 37, 22, 90]
[13, 22, 37, 40, 71, 75, 90, 91, 91, 99]
四、插入法排序
public static void INSort(int[] list) {
for (int i=1; i<list.length; i++) {
for (int j=i; j>0; j--) {
if (list[j]<list[j-1]) {
int temp = list[j];
list[j] = list[j-1];
list[j-1] = temp;
} else break;
}
}
}
public static void main(String[] args) {
int[] list2 = getArr();
System.out.println(Arrays.toString(list2));
INSort(list2);
System.out.println(Arrays.toString(list2));
}
[31, 99, 20, 42, 36, 10, 45, 39, 87, 71]
[10, 20, 31, 36, 39, 42, 45, 71, 87, 99]