选择排序
本文最后更新于:2021年9月2日 晚上
选择排序:合适的元素放在合适的位置
1、每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引处的只为最小值,最后可以找到最小值所在的索引。
2、交换第一个索引处和最小值所在的索引处的值
选择排序api实验:
package demo02.sort;
public class Selection {
/**
* 对数组a中的元素进行排序
*/
public static void sort(Comparable[] a){
for (int i = 0; i < a.length-1; i++) {
//定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素的位置
int minIndex = i;
for (int j = i+1; j < a.length; j++) {
if (greter(a[minIndex],a[j])){
minIndex = j;
}
}
//交换最小元素所在索引minIndex处的值和索引i处的值
exch(a,i,minIndex);
}
}
/**
* 比较v元素是否大于w元素
*/
private static boolean greter(Comparable v,Comparable w){
return v.compareTo(w)>0;
}
/**
* 数组元素i和j交换位置
*/
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
package demo02.test;
import demo02.sort.Selection;
import java.util.Arrays;
public class TestSelection {
public static void main(String[] args) {
//原始数据
Integer[] a = {4,6,8,7,9,2,10,1};
Selection.sort(a);
System.out.println(Arrays.toString(a));
}
}
运行结果:
选择排序时间复杂度分析:
本文作者: CodeAnime
本文链接: https://codeanime.cc/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!