Skip to main content
 首页 » 编程设计

java算法之插入排序

2022年07月18日51hnrainll
/** 
 * @desc: 插入排序 
 * @author: 毛会懂 
 * @create: 2020-12-23 13:25:00 
 **/ 
public class Insertion { 
    public static void sort(Comparable[] arr){ 
        for(int i = 1; i < arr.length;i++){ 
            for(int j = i;j > 0;j--){ 
                if(isExchange(arr[j-1],arr[j])){ 
                    exchange(arr,j-1,j); 
                }else{ 
                    //既然不交换了,那后面的for也不用交换了 
                    break; 
                } 
            } 
        } 
    } 
 
    private static Boolean isExchange(Comparable o1,Comparable o2){ 
        return o1.compareTo(o2) > 0; 
    } 
 
    private static void exchange(Comparable[] arr,int i,int j){ 
        Comparable temp = arr[i]; 
        arr[i] = arr[j]; 
        arr[j] = temp; 
    } 
} 
//插入排序 
public static void main2(String[] args) { 
    Integer[] arr = {10,8,20,30,5,7,4,12,40,30,1,2,4,3}; 
    Insertion.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/14179275.html