选择排序(selection sort)

选择排序也是最基本的排序算法之一,其算法复杂度为O(n^2),与待排序数组的内部结构没有关系。


算法简介
选择排序,顾名思义就是通过选择来排序。从一堆数中选出最小的放在第一位,在剩下的数中在选择最小的排在第二位。。。选择,就是一个比较的过程,从一堆数据中选择就是要在这个数据堆中一个一个进行比较。算法外层循环执行n次,每次一定进行i次比较操作,所以算法复杂度为n^2。非常直观的算法。

代码
package sorting;

public class Data {
	
	/**
	 * generate an unsorted array of length n
	 * @param n length
	 * @param max the maximum integer element of this array
	 * @return an unsorted array consists of elements range from 1 to max
	 */
	public static int[] getArray(int n, int max){
		int[] result = new int[n];
		for(int i =0; i < n; i++){
			result[i] = (int)(Math.random() * max + 1);
		}
		return result;
	}
	/**
	 * print the array
	 * @param arg array
	 */
	public static void printArray(int[] arg){
		StringBuffer temp = new StringBuffer();
		for(int i = 0; i < arg.length; i++){
			temp.append(arg[i] + "\t");
		}
		System.out.println(temp);
	}
}
package sorting;

public class SelectionSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SelectionSort ss = new SelectionSort();
		int[] data = Data.getArray(10, 100);
		System.out.print("Source data:\t");
		Data.printArray(data);
		ss.selectionSort(data);
		System.out.print("Sorted data:\t");
		Data.printArray(data);

	}
	
	public void selectionSort(int[] arg){
		int index = 0, min = 0, j = 0;
		// why i < length -1?
		// because when i equals length - 1, the rest of the array contains only 1 number.
		// after this time of loop, arg[arg.length - 1]must be the minimum one
		// in order to promote efficiency, wo should assign arg.length -  1 to a constant,
		// and use this constant in the compare statement 
		for(int i = 0; i < arg.length - 1; i++){
			index = i; 
			min = arg[i];
			// find the minimal number in the rest of the array
			for(j = i + 1; j < arg.length; j++){
				if(arg[j] < min){
					index = j;
					min = arg[j];
				}
			}
			//need switch
			if(index != i){
				arg[index] = arg[i];
				arg[i] = min;
			}
		}
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值