排序2:選擇排序
阿新 • • 發佈:2020-12-23
/**
* @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();
}
}