Java 氣泡排序 並與 Arrays.sort(arr) 比較
阿新 • • 發佈:2018-12-11
前段時間收到一個獵頭電話面試,問了關於氣泡排序的.我居然一時間想不起來...
只是回答了,大概倆個for迴圈什麼的...
今天想起來,複習下: jdk 1.8.0_181
package review; import java.util.Arrays; public class Jacktu{ public static void bubble_sort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; } } } } public static void main(String[] args) { int arrLength = 200000; int[] arr = new int[arrLength]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * arrLength); } int arr1[] = Arrays.copyOf(arr, arr.length); long start = System.currentTimeMillis(); bubble_sort(arr); System.out.println(System.currentTimeMillis() - start); start = System.currentTimeMillis(); Arrays.sort(arr1); System.out.println(System.currentTimeMillis() - start); } }
結果: 氣泡排序花費 50326 ms
Arrays.sort() 花費 30 ms