查找与排序 选择排序

本文详细介绍了选择排序,包括简单选择排序的原理和代码实现。简单选择排序是一种不稳定的排序算法,其时间复杂度为O(n^2),在最坏的情况下比较次数固定。此外,还提及了堆排序这一重点内容,虽然未给出具体实现,但在面试中经常被问到。
摘要由CSDN通过智能技术生成

简述选择排序

选择排序的基本思想是:每一趟(例如第i趟)在后面的 n-i+1 个待排序元素中选取关键字最小的元素,作为有序子序列的第i个元素,直到第 n-1 趟做完,待排序元素只剩下一个,就不用再选了。这里主要讲简单选择排序和堆排序(重点,面试中问到过)

一、简单选择排序
基本思想:假设排序表为 L[1…n] ,第i趟排序即从L[i,n] 中选择关键字最小的元素与 L(i) 交换,每一趟排序可以确定一个元素的最终位置,这样经过 n-1 趟排序就可以使整个排序表有序。

空间效率为O(1)

元素移动次数很少,当表有序时移动次数为0,但比较的次数与表的次序无关,所以时间复杂度始终为O(n2)

不稳定的算法

在这里插入图片描述


`

实现代码

/**
	 *********************
	 * Selection sort. All data are valid.
	 *********************
	 */
	public void selectionSort() {
		DataNode tempNode;
		int tempIndexForSmallest;

		for (int i = 0; i < length - 1; i++) {
			// Initialize.
			tempNode = data[i];
			tempIndexForSmallest = i;
			for (int j = i + 1; j < length; j++) {
				if (data[j].key < tempNode.key) {
					tempNode = data[j];
					tempIndexForSmallest = j;
				} // Of if
			} // Of for j

			// Change the selected one with the current one.
			data[tempIndexForSmallest] = data[i];
			data[i] = tempNode;
		} // Of for i
	}// Of selectionSort

	/**
	 *********************
	 * Test the method.
	 *********************
	 */
	public static void selectionSortTest() {
		int[] tempUnsortedKeys = { 5, 3, 6, 10, 7, 1, 9 };
		String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
		DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);

		System.out.println(tempDataArray);

		tempDataArray.selectionSort();
		System.out.println("Result\r\n" + tempDataArray);
	}// Of selectionSortTest

运行结果

-------selectionSortTest-------
I am a data array with 7 items.
(5, if)  (3, then)  (6, else)  (10, switch)  (7, case)  (1, for)  (9, while)  
Result
I am a data array with 7 items.
(1, for)  (3, then)  (5, if)  (6, else)  (7, case)  (9, while)  (10, switch)  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值