冒泡,選擇,插入三排序

這三種排序的時間複雜度都是指數級的,因此在實際項目中並不推薦。數組

/**
 * Created by Administrator on 2018-02-17.
 */
public class Sort {
    static final int SIZE = 10;
    public static void BubbleSort(int[] a) {
        int temp;
        if(a.length > 1) {
            for (int i = 1; i < a.length; i++) {
                for (int j = 0;j < a.length - i;j++) {
                    if(a[j] > a[j+1]) {
                        temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                    }
                }
                System.out.print("第" + i +"步排序結果:");
                for (int k = 0;k < a.length;k++) {
                    System.out.print(" " + a[k]);
                }
                System.out.print("\n");
            }
        }
    }
    
   public static void selectSort(int[] a) {
    int index;
    int temp;
    for (int i = 0;i < a.length - 1;i++) {
        index = i;
        for (int j = i + 1;j < a.length;j++) {
            if(a[j] < a[index]) {
                index = j;
            }
        }
        if(index != i) {
            temp = a[i];
            a[i] = a[index];
            a[index] = temp;
        }
        System.out.print("第" + i + "步排序結果:");
        for (int h = 0;h < a.length;h++) {
            System.out.print(" " + a[h]);
        }
        System.out.print("\n");
    }
}
public static void insertionSort(int[] a) {
    int i,j,t,h;
    for (i = 1;i < a.length;i++) {
        t = a[i];
        j = i - 1;
        while (j >= 0 && t < a[j]) {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = t;
        System.out.print("第" + i + "步排序結果:");
        for (h = 0;h < a.length;h++) {
            System.out.print(" " + a[h]);
        }
        System.out.print("\n");
    }
}
public static void main(String[] args) {
        int[] shuzu = new int[SIZE];
        int i;
        for (i = 0;i < SIZE;i++) {
            shuzu[i] = (int)(100 + Math.random() * (100 + 1));
        }
        System.out.print("排序前的數組爲:\n");
        for (i = 0;i <SIZE;i++) {
            System.out.print(shuzu[i] + " ");
        }
        System.out.print("\n");
        BubbleSort(shuzu);      //selectSort或者insertionSort
        System.out.print("排序後的數組爲:\n");
        for (i = 0;i < SIZE;i++) {
            System.out.print(shuzu[i] + " ");
        }
        System.out.print("\n");
}
}
相關文章
相關標籤/搜索