排序算法-直接选择排序

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 + " ");
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值