日撸代码300行:第47天(选择排序)

时间:2025-02-19 09:31:47
/** * ***************************************************** * Selection sort. All data are valid. * ***************************************************** */ public void selectionSort() { DataNode tempNode; int tempIndexForSmallest; for (int i = 0; i < data.length - 1; i++) { //Initialize tempNode = data[i]; tempIndexForSmallest = i; //Find the smallest key. for (int j = i + 1; j < data.length; j++) { if (data[j].key < tempNode.key) { tempNode = data[j]; tempIndexForSmallest = j; }//of if }//of for j //The minimum value is placed in the current first place 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 /** * ******************************************************** * The entrance of program. * * @param args Not used now. * ******************************************************** */ public static void main(String args[]) { System.out.println("\r\n-------selectionSortTest-------"); selectionSortTest(); }//of main