2017-02-10 42 views
-1

我最近經歷了一些排序算法,包括泡泡排序,選擇排序,插入排序,合併排序,堆排序,快速排序等,當我突然想到一個問題,當我們使用Java中的函數sort()或者Sorting算法執行的其他語言的函數sort()是否與所有其他語言的排序函數的算法相同?試圖瞭解在Java中排序

例如,這是我在Java代碼:

import java.util.Arrays; 

    public class ArrayDemo { 

    public static void main(String[] args) { 

    int i; 
    int A[] = {2, 1, 9, 6, 4}; 


    for (i = 0; i < A.length ; i++) 
    { 
    System.out.println("Number = " + A[i]); 
    } 

    // sorting array 
    Arrays.sort(A); 


    System.out.println("The sorted int array is:"); 
    for (i = 0; i < A.length ; i++) 
    { 
     System.out.println("Number = " + A[i]); 
    } 
    } 
} 

而且,我想知道哪個排序算法做Arrays.sort()使用排序的陣列A.

感謝

+3

請參見[用於java.util.Arrays中文檔】(https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html) – khelwood

+0

由於@khelwood –

回答

1

正如你可以看到here,他們使用DualPivotQuicksort算法。

/** 
65  * Sorts the specified array into ascending numerical order. 
66  * 
67  * <p>Implementation note: The sorting algorithm is a Dual-Pivot  Quicksort 
68  * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm 
69  * offers O(n log(n)) performance on many data sets that cause other 
70  * quicksorts to degrade to quadratic performance, and is typically 
71  * faster than traditional (one-pivot) Quicksort implementations. 
72  * 
73  * @param a the array to be sorted 
74  */ 
75  public static void sort(int[] a) { 
76   DualPivotQuicksort.sort(a); 
77  } 
+0

如果我記得是正確的,一個基元數組的快速排序的變體,以及一個對象數組合並排序的變體(穩定性,因爲對象通常在內部作爲指向對象的指針來實現,合併排序應該更快), – rcgldr

+0

@ rcgldr mergesort上的變體在https://en.wikipedia.org/wiki/Timsort中描述。 – btilly