黑马程序员技术交流社区

标题: 选择排序 [打印本页]

作者: 陈熙    时间: 2015-8-14 22:09
标题: 选择排序
public class SelectSortDemo {
       
        public static void main(String[] args) {
               
                // 定义一个数组
                int[] arr = { 24, 69, 80, 57, 13 } ;
                System.out.print("排序前: ");
                BubbleSortDemo.print(arr);
               
                // 选择排序
                selectSort2(arr);
               
                System.out.print("排序后: ");
                BubbleSortDemo.print(arr);
               
        }
       
        /**
         * 选择排序
         * @param arr
         */
        public static void selectSort2(int[] arr){
               
                for(int index = 0 ; index < arr.length - 1 ; index++ ){
                        for(int x = 1 + index ; x < arr.length ; x++){
                                if(arr[index] > arr[x]){
                                        int temp = arr[x] ;
                                        arr[x] = arr[index] ;
                                        arr[index] = temp ;
                                }
                        }
                }
               
        }
       
        /**
         * 选择排序推导过程
         * @param arr
         */
        public static void selectSort1(int[] arr){
               
                // 第一次排序
                int index = 0 ;
                for(int x = 1 + index ; x < arr.length ; x++){
                        if(arr[index] > arr[x]){
                                int temp = arr[x] ;
                                arr[x] = arr[index] ;
                                arr[index] = temp ;
                        }
                }
               
                // 第二次排序
                index = 1 ;
                for(int x = 1 + index ; x < arr.length ; x++){
                        if(arr[index] > arr[x]){
                                int temp = arr[x] ;
                                arr[x] = arr[index] ;
                                arr[index] = temp ;
                        }
                }
               
                // 第三次排序
                index = 2 ;
                for(int x = 1 + index ; x < arr.length ; x++){
                        if(arr[index] > arr[x]){
                                int temp = arr[x] ;
                                arr[x] = arr[index] ;
                                arr[index] = temp ;
                        }
                }
               
                // 第四次排序
                index = 3 ;
                for(int x = 1 + index ; x < arr.length ; x++){
                        if(arr[index] > arr[x]){
                                int temp = arr[x] ;
                                arr[x] = arr[index] ;
                                arr[index] = temp ;
                        }
                }
               
        }

}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2