日撸代码300行:第47天(选择排序)

代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863

选择排序算法理解可参考:https://zhuanlan.zhihu.com/p/29889599

1、选择排序算法思想比较简单,关键有两点。第一点,选择当前的最值(最大或最小);第二点,将最值放在其改在的位置,即最小值依次轮次的首位(按照最大值排序则依次放在末尾)。
2、两层for循环,第二层循环是为了找到当前循环内的最小值,键值对和序列分别存在tempNode和tempIndexForSmallest中。第一层循环确定当前是在排第几个数,并将内层for循环找到的最小值和首位的data[i]交换。

	/**
	 * *****************************************************
	 * Selection sort. All data are valid.
	 * *****************************************************
	 */
	public void selectionSort() {
		DataNode tempNode;
		int tempIndexForSmallest;
		
		for (int i = 0; i < data.length - 1; i++) {
			//Initialize
			tempNode = data[i];
			tempIndexForSmallest = i;
			//Find the smallest key.
			for (int j = i + 1; j < data.length; j++) {
				if (data[j].key < tempNode.key) {
					tempNode = data[j];
					tempIndexForSmallest = j;
				}//of if
			}//of for j
			
			//The minimum value is placed in the current first place
			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

	/**
	 * ********************************************************
	 * The entrance of program.
	 * 
	 * @param args  Not used now.
	 * ********************************************************
	 */
	public static void main(String args[]) {	
		System.out.println("\r\n-------selectionSortTest-------");
		selectionSortTest();
	}//of main
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值