1. 程式人生 > >Java三種排序:冒泡,選擇,插入排序

Java三種排序:冒泡,選擇,插入排序

反序 三種 blog void bubble public string length 選擇

三種排序:冒泡,選擇,插入排序

        public static void bubbleSort(int[] source){
            // 交換類排序思想: 兩兩比較待排序的關鍵字,發現記錄相反則交換,直到沒有反序的記錄。
            for(int i = source.length - 1; i > 0; i--){
                for(int j = 0; j < i; j++){
                    if(source[j] > source[j + 1]){
                        swap(source, j, j+1);
                    }
                }
            }
        }

        
        public static void selectSort(int[] source){
            // 選擇類排序思想:首先在未排序的序列中找到最小元素,存放到排序序列的起始位置,
            // 然後再從剩余未排序的元素中找到下一個最小元素,放到已排序序列的末尾。
            for (int i = 0; i < source.length; i++){
                for (int j = i+1; j < source.length; j++){
                    if (source[j] > source[i]){
                        swap(source, i, j);
                    }
                }
            }
            
        }
        // 從第一個元素開始,該元素可以認為已經被元素
        // 取出下一個元素,在已經拍序的元素中從後往前掃描,如果該元素大於新一個,則將該元素移到下一個
        public static void insertSort(int[] source){
            for(int i = 1; i < source.length; i++){
                for(int j = i ; (j > 0) && (source[j] < source[j - 1]); j--){
                    swap(source, j, j-1);
                }
                
            }
        }
        
        private static void swap(int[] source, int x, int y){
            int temp = source[x];
            source[x] = source[y];
            source[y] = temp;
        }
        
        public static void main(String[] args){
            int[] a = {4, 2, 1, 3, 4, 6, 7, 8, 0};
            int i;
            bubbleSort(a);
            for (i = 0;i<a.length;i++){
                System.out.printf("%d ", a[i]);
            }
            

  

Java三種排序:冒泡,選擇,插入排序