原理:每一趟從待排序的記錄中選出最小的元素,順序放在已排好序的序列最後,直到全部記錄排序完畢。
簡單選擇排序的基本思想:給定數組:int[] arr={裡面n個資料};第1趟排序,在待排序資料arr[1]~arr[n]中選出最小的資料,将它與arrr[1]交換;第2趟,在待排序資料arr[2]~arr[n]中選出最小的資料,将它與r[2]交換;以此類推,第i趟在待排序資料arr[i]~arr[n]中選出最小的資料,将它與r[i]交換,直到全部排序完成。
舉例:數組 int[] arr={5,2,8,4,9,1};
-------------------------------------------------------
第一趟排序: 原始資料:5 2 8 4 9 1
最小資料1,把1放在首位,也就是1和5互換位置,
排序結果:1 2 8 4 9 5
-------------------------------------------------------
第二趟排序:
第1以外的資料{2 8 4 9 5}進行比較,2最小,
排序結果:1 2 8 4 9 5
-------------------------------------------------------
第三趟排序:
除1、2以外的資料{8 4 9 5}進行比較,4最小,8和4交換
排序結果:1 2 4 8 9 5
-------------------------------------------------------
第四趟排序:
除第1、2、4以外的其他資料{8 9 5}進行比較,5最小,8和5交換
排序結果:1 2 4 5 9 8
-------------------------------------------------------
第五趟排序:
除第1、2、4、5以外的其他資料{9 8}進行比較,8最小,8和9交換
排序結果:1 2 4 5 8 9
-------------------------------------------------------
注:每一趟排序獲得最小數的方法:for循環進行比較,定義一個第三個變量temp,首先前兩個數比較,把較小的數放在temp中,然後用temp再去跟剩下的資料比較,如果出現比temp小的資料,就用它代替temp中原有的資料。
java代碼
public class SelectSort {
private long []a;
public int elements;
public SelectSort(int max) {
a=new long[max];
elements=0;
// TODO Auto-generated constructor stub
}
public void insert(long value){
a[elements]=value;
elements++;
}
public void display(){
for(int j=0;j<elements;j++)
System.out.print(a[j]+" ");
System.out.println();
}
public void swap(int one,int two){
long temp=a[one];
a[one]=a[two];
a[two]=temp;
}
public void selectionSort(){
int out,in,min;
for(out=0;out<elements;out++)
{
min=out;//外層循環,假設第一個就是最小的
for(in=out+1;in<elements;in++)//内層循環,因為比較是以從他後面的一個元素開始比較
{
if(a[in]<a[min]){
min=in;
}
}
swap(out, min);
}
}
public static void main(String[] args) {
int max=100;
SelectSort selectSort=new SelectSort(max);
selectSort.insert(123);
selectSort.insert(21);
selectSort.insert(234);
selectSort.insert(322);
selectSort.insert(23);
System.out.println("沒有排序:");
selectSort.display();
System.out.println("排序後");
selectSort.selectionSort();
selectSort.display();
}
}