排序算法模板代码

1. 模板代码

public class SortExample {

    public static void sort(Comparable[] a){
        // 具体的算法实现
    }

    /***************************************************************************
     *  if v < w return true, otherwise return false.
     ***************************************************************************/
    private static boolean less(@NotNull Comparable v, @NotNull Comparable w){
        return v.compareTo(w) < 0;
    }

    /***************************************************************************
     *  exchange a[i] and a[j]
     ***************************************************************************/
    private static void exch(Comparable[] a, int i, int j){
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    /***************************************************************************
     *  Check if array is sorted - useful for debugging.
     ***************************************************************************/
    private static boolean isSorted(Comparable[] a){
        int n = a.length;
        for (int i = 1; i < n; i++){
            if (less(a[i+1], a[i])){
                return false;
            }
        }
        return true;
    }

    /***************************************************************************
     *  print array to standard output
     ***************************************************************************/
    public static void show(Comparable[] a){
        for (int i = 0; i < a.length; i++){
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    /**
     * Reads in a sequence of strings from standard input; selection sorts them; 
     * and prints them to standard output in ascending order. 
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);
        String sentences = scanner.nextLine();
        String[] words = sentences.split(" ");
        sort(words);
        show(words);
    }
}

等待补充…

猜你喜欢

转载自blog.csdn.net/qq_38182125/article/details/94767071