选择排序java实现

package algorithm;

public class SelectSort {
	public static void main(String[] args) {
		int[] a = {6,2,5,4,7,1,3,9,8};
		selectSort(a, a.length);
	//	selectSort2(a); 
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
	/**
	 * 找出最大数的下标
	 * @param a
	 * @return
	 */
	private static int findMaxPostion(int[] a, int n){
		int max = a[0];
		int pos = 0;
		for (int i = 0; i < n; i++) {
			if(a[i] > max){
				max = a[i];
				pos = i;
			}
		}
		return pos;
	}
	
	/**
	 * 找出每次比较数的最大值跟数组的最后一个元素进行交换
	 * @param a
	 * @param n
	 */
	private static void selectSort(int[] a,int n){
		while(n > 1){
			int postion = findMaxPostion(a,n);
			int temp = a[postion];
			a[postion] = a[n-1];
			a[n-1] = temp;
			n--;
		}
	}
	
	
	private static void selectSort2(int[] a){
		for (int i = 0,k = 0; i < a.length; i++,k = i) {
			for (int j = i+1; j < a.length; j++) {
				if(a[k] > a[j]){
					k = j;
				}
			}
			if(i != k){
				int temp = a[i];
				a[i] = a[k];
				a[k] = temp;
			}
		}
	}

}

 

点赞