Skip to main content
 首页 » 编程设计

java算法之选择排序

2022年07月18日146softidea
/** 
 * @desc: 选择排序 
 * @author: 毛会懂 
 * @create: 2020-12-23 13:52:00 
 **/ 
public class Selection { 
 
    public static void sort(Comparable[] arr){ 
        for(int i = 0; i < arr.length - 1;i++){ 
            int minIndex = i; 
            for(int j = i + 1;j < arr.length;j++){ 
                if(isExchange(arr[minIndex],arr[j])){ 
                    minIndex = j; 
                } 
            } 
            //没有选择到更小的data,则不交换 
            if(i != minIndex) { 
                swap(arr, i, minIndex); 
            } 
        } 
    } 
 
    private static Boolean isExchange(Comparable o1,Comparable o2){ 
        return o1.compareTo(o2) > 0; 
    } 
 
    private static void swap(Comparable[] arr,int i,int j){ 
        Comparable temp = arr[i]; 
        arr[i] = arr[j]; 
        arr[j] = temp; 
    } 
} 
 
//选择排序 
public static void main(String[] args) { 
    Integer[] arr = {10,8,20,30,5,7,4,12,40,30,1,2,4,3,100,5,32,45,23,66,45,7,55,79,6}; 
    Selection.sort(arr); 
    Arrays.asList(arr).forEach(System.out::println); 
 
    Person[] persions = {new Person("b",11),new Person("a",10),new Person("c",12),new Person("b",111), 
            new Person("a",5),new Person("c",4)}; 
    Insertion.sort(persions); 
    for (Person person : persions) { 
        System.out.println(person); 
    } 
} 
 
附: 
/** 
 * @desc: 实现Comparable接口 
 * @author: 毛会懂 
 * @create: 2020-12-23 13:36:00 
 **/ 
public class Person implements Comparable<Person>{ 
    private String name; 
 
    private Integer age; 
 
    public Person(String name, Integer age) { 
        this.name = name; 
        this.age = age; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
 
    public Integer getAge() { 
        return age; 
    } 
 
    public void setAge(Integer age) { 
        this.age = age; 
    } 
 
    @Override 
    public String toString() { 
        return "Persion{" + 
                "name='" + name + '\'' + 
                ", age=" + age + 
                '}'; 
    } 
 
    @Override 
    public int compareTo(Person o) { 
        return this.age - o.getAge(); 
    } 
} 

  


本文参考链接:https://www.cnblogs.com/maohuidong/p/14179337.html
阅读延展