java简单选择排序

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class T1 {

    public static void main(String[] args) throws ParseException {
        
        //选择排序 由大到小
        int[] a = {9,2,2,4,5,6};
        int j;
        int i;
        int temp;
        
        for(i = 0; i < a.length; i++){
            for(j = i; j < a.length; j++)
             if(a[i] > a[j]){
                 temp = a[i];
                 a[i] = a[j];
                 a[j] = temp;
             }
        }

        
        for(i = 0 ; i < a.length ; i++){
            System.out.println(a[i]);
        }
    }

 

 

下面的排序也类似选择排序 寻找未排序的值的最大值 与头部交换

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class T1 {

    public static void main(String[] args) throws ParseException {
        
        //选择排序 由大到小
        int[] a = {1,2,2,0,-5,6};
        int max = a[0];//先假设数组的第一个值为最大值;
        int maxIndex = 0;
        int j;
        int i;
        int temp;
        
        for(i = 0; i < a.length; i++){
            for(j = i; j < a.length; j++)
             if(max < a[j]){
                max = a[j];
                maxIndex = j;
             }

            temp = a[i];
            a[i] = max;
            a[maxIndex] = temp;
            max = 0;
        }

        
        for(i = 0 ; i < a.length ; i++){
            System.out.println(a[i]);
        }
    }
    
    
}
 


版权声明:本文为weixin_37826998原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。