A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈熙 中级黑马   /  2015-8-14 22:09  /  350 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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 ;
                        }
                }
               
        }

}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马