选择排序
选择排序思路
通过选择和交换
首先从原始数组中选择最小的1个数据,将其和位于第一个位置的数据进行交换
接着从n-1个数据中选择次小的1个数据,将其和第2个位置的数据交换
然后不断重复上述过程,直到最后的两个数据完成交换。
时间复杂度:O(n^2) 最好情况:O(n^2) 最坏情况:O(n^2)
空间复杂度:O(1)
稳定性:不稳定
复杂性:简单
Java实现代码
package com.wangjun.arithmetic;
import java.util.Arrays;
/*
* 选择排序
*/
public class SortSelect {
public static void main(String[] args) {
int[] arr = {2,3,7,5,43,8,9,0,3,1};
SortSelect ss = new SortSelect();
ss.sortSelect(arr);
System.out.println(Arrays.toString(arr));
}
/*
通过选择和交换:
1,首先从原始数组中选择最小的1个数据,将其和位于第一个位置的数据进行交换
2,接着从n-1个数据中选择次小的1个数据,将其和第2个位置的数据交换
3,然后不断重复上述过程,直到最后的两个数据完成交换。
*/
public void sortSelect(int[] arr) {
int len = arr.length;
for(int i = 0; i < len - 1; i++) {
int index = i;
for(int j = i + 1; j < len; j++) {
if(arr[j] < arr[index]) {
index = j;
}
}
if(index != i) {
int tem = arr[i];
arr[i] = arr[index];
arr[index] = tem;
}
}
}
}
Last updated
Was this helpful?