選擇排序

先找出最小的值並將其與a[1]中的元素進行交換,接着找出a數組中次最小的元素與a[2]進行交換,一次找出其他的


/**
	 * 選擇排序
	 * 對指定數組進行排序
	 * @param a   要排序的數組
	 */
	public static int[] selectSort(int[] a ){
		if(a==null||a.length<0){
			return null;
		}
		for(int i=0 ; i<a.length-1; i++){    //             
			int key = i;   //默認將第一個元素的作爲最小值                           
			for(int j = i+1; j<a.length; j++){  //         
				if(a[key]>a[j]){              //        
					key = j;     //選擇出最小的值的下標
				}
			}
			if(i!=key){
				swap(a,key,i);   //交換值
			}
		}
		return a;
	}
	/**
	 * 交換數組中的兩個數
	 * @param a  要交換的數組
	 * @param x  要交換的索引
	 * @param y  要交換的索引
	 */
	public static void swap(int[] a ,int x ,int y){
		int temp = a[x];
		a[x] = a[y];
		a[y] = temp;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章