日撸代码300行学习笔记 Day 47

1. 简单选择排序

简单选择排序顾名思义,思想真的很简单,每一趟排序中选择关键字最小的元素与其交换,每一趟排序就可以确定一个元素的最终位置,这样,经过n-1趟排序就可使整个排序表有序。

2. 代码

/**
	 * 
	 ***********************************
	 * @Title: selectionSort   
	 * @Description:  Selection sort
	 * @param:       
	 * @return: void       
	 ***********************************
	 */
	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
			data[tempIndexForSmallest] = data[i];
			data[i] = tempNode;
		}//Of for i
	}//Of selectionSort
	
	/**
	 * 
	 ***********************************
	 * @Title: selectionSortTest   
	 * @Description:  test method
	 * @param:       
	 * @return: void       
	 ***********************************
	 */
	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
	/**
	 * 
	 ***********************************
	 * @Title: main
	 * @Description:
	 * @param: @param args
	 * @return: void
	 ***********************************
	 */
	public static void main(String args[]) {
		System.out.println("\r\n-------selectionSortTest-------");
		selectionSortTest();
	}// Of main

3.总结 

简单选择排序中,要使用常数个辅助单元,空间效率为O(1)。在简单选择排序中,元素移动的操作次数很少,不会超过3(n-1)次。最好的情况是移动0次,这时代表初表直接有序。元素间的比较次数与序列的初始状态无关,始终n(n-1)/2次,因此时间复杂度始终为O(n2)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值