1. 简单选择排序
简单选择排序顾名思义,思想真的很简单,每一趟排序中选择关键字最小的元素与其交换,每一趟排序就可以确定一个元素的最终位置,这样,经过n-1趟排序就可使整个排序表有序。
2. 代码
/**
*
***********************************
* @Title: selectionSort
* @Description: Selection sort
* @param:
* @return: void
***********************************
*/
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
// change
data[tempIndexForSmallest] = data[i];
data[i] = tempNode;
}//Of for i
}//Of selectionSort
/**
*
***********************************
* @Title: selectionSortTest
* @Description: test method
* @param:
* @return: void
***********************************
*/
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
/**
*
***********************************
* @Title: main
* @Description:
* @param: @param args
* @return: void
***********************************
*/
public static void main(String args[]) {
System.out.println("\r\n-------selectionSortTest-------");
selectionSortTest();
}// Of main
3.总结
简单选择排序中,要使用常数个辅助单元,空间效率为O(1)。在简单选择排序中,元素移动的操作次数很少,不会超过3(n-1)次。最好的情况是移动0次,这时代表初表直接有序。元素间的比较次数与序列的初始状态无关,始终n(n-1)/2次,因此时间复杂度始终为O(n2)。