简介:选择排序是一个时间复杂度为O(N^2)的基本排序算法,当然也有其适用的场景,比如说该算法的易于实现的特性,可应用于对某些实际问题的快速实现上.
原理:从未排序的数据中,选出最小的数据,然后与未排序的第一个数据进行比较交换操作,直到所有的数据都排好序.
步骤:
①在未进行排序的数据中,寻找到最小的数据,假设为A,并记录下该下标
②用未排序的第一个数据B与从①中得到的数据A进行比较,如果A小于B,则交换A与B,否则不交换.
③重复以上的①②步骤,直到所有的数据都排好序.
代码是思路的体现,因此在写代码之前一定要理清楚思路.
/**
* 规则 [0,i-1] 采用前闭后闭的原则进行算法的编写,牢记. 顺序为 从小到大排序
*
* @author JamesWang
*
*/
public class SelectionSort implements IPerformance {
private int[] arr;
public SelectionSort(int[] arr) {
this.arr = arr;
}
@Override
public void performance() {
int minIndex;
for (int i = 0; i <= arr.length - 1; i++) {// [0,arr.length - 1] 前闭 后闭
minIndex = i;// 默认当前i为最小值的下标
for (int j = i + 1; j <= arr.length - 1; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
//进行比较交换操作
if(arr[minIndex] != arr[i]) {//只有当两个下标对应的值不相等再进行交换
arr[i] = arr[i] + arr[minIndex];
arr[minIndex] = arr[i] - arr[minIndex];
arr[i] = arr[i] - arr[minIndex];
}
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
int[] arr = SortUtils.createArray(100);//创建一个数值范围为[0,100)包含有100个元素的数组
PerformanceUtils performanceUtils = new PerformanceUtils(new SelectionSort(arr));//创建代理类
performanceUtils.performance();//执行代理方法
System.out.println(SortUtils.getString(arr));
}
}
public interface IPerformance {
public void performance();
}
public class SortUtils {
public static int[] createArray(int count) {
int[] arr = new int[count];
Random random = new Random();
for (int index = 0; index < count; index++) {
arr[index] = random.nextInt(count);
}
return arr;
}
public static int[] copy(int[] arr) {
return Arrays.copyOf(arr, arr.length);
}
public static String getString(int[] arr) {
StringBuffer sb = new StringBuffer();
for(int a : arr) {
sb.append( a + ",");
}
return sb.toString();
}
}
/**
* 使用代理模式来进行性能的测试
*
* @author JamesWang Create on 2018年1月4日 下午4:05:35
*/
public class PerformanceUtils implements IPerformance {
private IPerformance performance;
public PerformanceUtils(IPerformance performance) {
this.performance = performance;
}
@Override
public void performance() {
long startTime = System.currentTimeMillis();
performance.performance();
System.out.println("运行时间为:" + (System.currentTimeMillis() - startTime) + "毫秒");
}
}