Day 47 —— Selection Sort
1. Description
今天学的内容是选择排序,是一个简单直观的算法。
其内容核心是在未排序列中找到最小的元素,然后将其和当前循环的起始元素交换位置。然后重复这个操作,这样每次操作下来当前循环内最小的元素都会被换到序列的开头。当所有的循环结束,所有的元素都有序了。
2. Code
public void SelectionSort() {
DataNode tempNode;
int tempIndexForSmallest;
for (int i = 0; i < length - 1; i++) {
// Initialize.
tempNode = data[i];
tempIndexForSmallest = i;
for (int j = i + 1; j < length; j++) {
if (data[j].key < tempNode.key) {
tempNode = data[j];
tempIndexForSmallest = j;
} // Of if
} // Of for j
// 将上面选择出的最小的元素和当前循环的第一个元素交换位置。
data[tempIndexForSmallest] = data[i];
data[i] = tempNode;
} // Of for i
}// Of selectionSort
/**
*********************
* Test the method.
*********************
*/
public static void SelectionSortTest() {
int[] tempUnsortedKeys = { 5, 3, 6, 10, 7, 1, 9 };
String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.SelectionSort();
System.out.println("Result\r\n" + tempDataArray);
}// Of selectionSortTest
运行结果: