Last active
May 8, 2017 06:49
-
-
Save claudhu/7db6dabbad3602c7ac9efc678a2912fe to your computer and use it in GitHub Desktop.
java 選擇排序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
author: Claud Hu | |
desc: Selection Sort,依序由小到大的排列,從第0個位置開始排序 | |
舉例來說 | |
original array: [632,33,55,1,88] | |
round 1 : [1,632,55,33,88] 第1輪結束,第0個位置是最小值 | |
round 2 : [1,33,632,55,88] 第2輪結束,比第0個位置大,但比其他數值小 | |
round 3 : [1,33,55,632,88] 第3輪結束,比第1個位置大,但比其他數值小 | |
round 4 : [1,33,55,88,632] 第4輪結束,比第2個位置大,但比其他數值小 | |
finish: [1,33,55,88,632] | |
*/ | |
class SelectionSort{ | |
public static void main(String args[]){ | |
int[] intArray = {1, 2, 5, 11, 632, 1, 22}; | |
for(int i=0; i<intArray.length; i++){ | |
int minimum = i; // 設定minimum 此處用於表示最小的Index,第一輪由Index:0開始...Index後續會一直增加直到最後一個為止 | |
for(int j= i+1; j <intArray.length; j++){ //這個迴圈是用於比較數值的大小,以當前的element向後->比較 | |
if (intArray[j]<intArray[minimum]) // 如果後面的數值有小於當前的數值 | |
minimum = j; // 將minimum的index改為j | |
} | |
//lets REAL number swap... | |
int temp; //佔存變數: 用於交換時使用 | |
/** | |
Triangle Swap.... 我們要AB交換 但是Call by Reference 需要new一個Variable來輔助交換 | |
A | |
B C(temp) | |
Step1. 先把B 傳給C | |
Step2. 再把A 傳給B | |
Step3. 再把C 傳給A | |
這樣AB就交換了... | |
**/ | |
temp = intArray[i]; | |
intArray[i]= intArray[minimum]; | |
intArray[minimum] = temp; | |
} | |
/** 依序印出數值 */ | |
for(int i = 0 ; i <intArray.length;i++){ | |
System.out.println(intArray[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment