选择排序(时间复杂度O(n^2))

代码(带优化)

public class SelectSort {
	
	static int[] arr = {6,7,0,-5,8,1,3,2};
	public static void main(String[] args) {
		System.out.println("排序前:" + Arrays.toString(arr));
		selectSort(arr);
		System.out.println("排序后:" + Arrays.toString(arr));
	}

	private static void selectSort(int[] arr) {
		
		for (int i = 0; i < arr.length - 1; i++) {
			//假定最小值的下标是i
			int minIndex = i;
			//假定最小值是min
			int min = arr[i];
			for (int j = i + 1; j < arr.length; j++) {
				if(min > arr[j]){
					min = arr[j];
					minIndex = j;
				}
			}
			//已经排好序的,不用再交换
			if(minIndex != i){
				arr[minIndex] = arr[i];
				arr[i] = min;
			}
			System.out.println("第 " + (i + 1) + "趟排序结果是:" + Arrays.toString(arr));
		}
	}
}

结果

image

性能测试(8万个随机数)

image
(867)不到1s,冒泡排序10s多

原文地址:https://www.cnblogs.com/kaka-qiqi/p/15262264.html