选择排序-java
package 数据结构与算法.排序算法;
import java.util.Arrays;
/**
* @Auther: IsAriel~~
* @Date: 2021/4/14 21:08
* @Description:选择排序算法
*/
public class 选择排序 {
/**
* 对数组中的元素排序
*/
public static void sort(Comparable[] comparable) {
for (int i = 0; i <= comparable.length - 1; i++) {
Integer min = i;
for (int j = i+1; j <= comparable.length - 1; j++) {
if (greaterThan(comparable[min], comparable[j])) {
min = j;
}
}
exchange(comparable,i,min);
}
}
/**
* 比较v元素是否大于w元素
*/
public static boolean greaterThan(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
/**
* 数据i和j交换位置
*/
public static void exchange(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Integer[] arr = {3, 6, 4, 7, 3, 2, 1};
sort(arr);
System.out.println(Arrays.toString(arr));
}
}
结果: