直接选择排序

package Sort;

import org.junit.Test;

import Sort.utils.Swap;

/*
 * 	直接选择排序为不稳定排序
 * 	直接选择排序的最好时间复杂度和最差时间复杂度都是O(n^2),
 * 	因为即使数组一开始就是正序的,也需要将两重循环进行完,平均时间复杂度也是O(n^2)。
 * 	空间复杂度为O(1),因为不占用多余的空间。直接选择排序是一种原地排序(In-place sort)
 * 	并且稳定(stable sort)的排序算法,优点是实现简单,占用空间小,缺点是效率低,
 * 	时间复杂度高,对于大规模的数据耗时长
 *
 */
public class SelectSort {
	public static <T extends Comparable<T>> void selectSort(T[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			int minIndex = i;
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[j].compareTo(arr[minIndex]) < 0) {
					minIndex = j;
				}
			}
			if (minIndex != i) {
				Swap.swap(arr, minIndex, i);
			}
		}
	}

	// public static void swap(Object[] obj, int minIndex, int i) {
	// Object tep = obj[minIndex];
	// obj[minIndex] = obj[i];
	// obj[i] = tep;
	// }

	@Test
	public void testSelectSort() {
		Integer[] arr = { 34, 8, 64, 51, 32, 21 };
		selectSort(arr);
		for (Integer i : arr) {
			System.out.print(i + " ");
		}
	}
}

posted @ 2018-04-08 15:58  wei1  阅读(97)  评论(0)    收藏  举报