Insertion Sort 與 Merge Sort的性能比較(Java)
阿新 • • 發佈:2019-03-12
復雜 隨機 lse ons spa tar ray tostring style
public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] a = new int[n]; //生成n個隨機數(0至100) for(int i = 0; i < n; i++) a[i] = (int)(Math.random() * 100);/*long start = System.currentTimeMillis(); InsertionSort(a); long end = System.currentTimeMillis();*/ //100000個測試數據InsertionSort的排序時間約為2800ms /*System.out.println(Arrays.toString(a)); System.out.println(start); System.out.println(end); System.out.printf("The time is: %d", end - start);*/
//獲取當前時間(ms) long start = System.currentTimeMillis(); divide(a, 0, a.length - 1); long end = System.currentTimeMillis(); //100000000個測試數據MergeSort的排序時間約為12000ms 10000000個測試數據用時約為1200ms //相對於平均時間復雜度O(n^2)的插入排序 隨著測試數據數量級的增長 性能提升極大 //System.out.println(Arrays.toString(a));System.out.println(start); System.out.println(end); System.out.println("The time is: " + (end - start)); } /*public static void InsertionSort(int[] a) { for(int i = 1; i < a.length; i++) { int key = a[i]; int j; for(j = i - 1; j >= 0 && key < a[j]; j--) a[j + 1] = a[j]; a[j + 1] = key; } }*/ public static void divide(int[] a, int front, int rear) { if(rear <= front) return; int mid = front + (rear - front) / 2; divide(a, mid + 1, rear); divide(a, front, mid); merge(a, front, mid, rear); } public static void merge(int[] a, int front, int mid, int rear) { int[] b = new int[rear - front + 1]; int i = front, j = mid + 1, k = 0; while(i <= mid && j <= rear) if(a[i] < a[j]) b[k++] = a[i++]; else b[k++] = a[j++]; if(i > mid) while(j <= rear) b[k++] = a[j++]; else while(i <= mid) b[k++] = a[i++]; for(int t = 0, q = front; t < b.length; t++, ++q) a[q] = b[t]; }
Insertion Sort 與 Merge Sort的性能比較(Java)