Java中利用數組進行數字排序一般有4種方法:選擇排序法、冒泡法、快速排序法、插入排序法。
選擇排序是先將數組中的第一個數作為最大或最小數,然后通過循環比較交換最大數或最小數與一輪比較中第一個數位置進行排序;
冒泡排序也是先將數組中的第一個數作為最大或最小數,循環比較相鄰兩個數的大小,滿足條件就互換位置,將最大數或最小數沉底;
快速排序法主要是運用Arrays類中的Arrays.sort方法()實現。
插入排序是選擇一個數組中的數據,通過不斷的插入比較最后進行排序。
選擇排序法
package com.lovo; public class Test01 { public static void main(String[] args) { int[] a = new int[5]; for(int i = 0; i < a.length; i++) { a[i] = (int) (Math.random() * 99 + 1); System.out.print(a[i] + " "); } // 簡單選擇排序 for(int i = 0; i < a.length - 1; i++) { int minIndex = i; for(int j = i + 1; j < a.length; j++) { if(a[j] < a[minIndex]) { minIndex = j; } } if(minIndex != i) { int temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp; } } for(int x : a) { System.out.print(x + " "); } } }
冒泡排序法
package com.lovo;
public class Test02 {
public static void main(String[] args) {
int[] a = new int[5];
for(int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 99 + 1);
System.out.print(a[i] + " ");
}
// 冒泡排序
boolean swapped = true; // 有沒有發生過交換
for(int i = 1; swapped && i <= a.length - 1; i++) {
swapped = false;
for(int j = 0; j < a.length - i; j++) {
if(a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
swapped = true;
}
}
}
for(int x : a) {
System.out.print(x + " ");
}
}
}
快速排序法
package com.lovo;
import java.util.Arrays;
public class Test03 {
// 快速排序法
public static void main(String[] args) {
int[] a = new int[5];
System.out.print("排序前: ");
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 99 + 1);
System.out.print(a[i] + " ");
}
System.out.print("\n排序后:");
Arrays.sort(a); // 進行排序
for (int x : a) {
System.out.print(x + " ");
}
}
}
