數組排序問題

將幾個數組的元素進行降序輸出

1.直接選擇排序 

/**

 * @(#)SelectSort.java
 *
 *
 * @author 
 * @version 1.00 2013/3/11
 */
 
 
public class SelectSort {
 
    public static void main (String[] args) {
//創建一個數組,數組元素亂序
    int[] array={63,89,45,56,59,65};
//創建直接排序類的對象
    SelectSort sorter=new SelectSort();
//調用排序類對象的方法將數組排序
    sorter.sort(array);
   
}
 
/**
*
*
* 要排序的數組
*
*/
public void sort(int[] array)
{
int index;
for(int i=1;i<array.length;i++)
{
index=0;
for(int j=1;j<array.length;j++)
{
if(array[j]>array[index])
{
index=j;
}
}
//交換在位置array.length-i和index(最大值)上的兩個數
int temp=array[array.length-i];//把第一個元素值保存到臨時變量中
array[array.length-i]=array[index];//吧第二個元素值保存到第一個元素單元中
array[index]=temp;//吧臨時變量也就是第一個元素原值保存到第二個元素中
}
showArray(array);//輸出直接選擇排序後的數組值
}
    public void showArray(int[] array)
    {
    for (int i:array)//遍歷數組
    {
    System.out.print(">"+i);//輸出每個數組元素的值
    }
    System.out.println();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章