日撸代码300行:第47天(选择排序)
代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863选择排序算法理解可参考:https://zhuanlan.zhihu.com/p/298895991、选择排序算法思想比较简单,关键有两点。第一点,选择当前的最值(最大或最小);第二点,将最值放在其改在的位置,即最小值依次
文章共898字 · 阅读需要大约3分钟
一键AI生成摘要,助你高效阅读
问答
·
代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863
选择排序算法理解可参考:https://zhuanlan.zhihu.com/p/29889599
1、选择排序算法思想比较简单,关键有两点。第一点,选择当前的最值(最大或最小);第二点,将最值放在其改在的位置,即最小值依次轮次的首位(按照最大值排序则依次放在末尾)。
2、两层for循环,第二层循环是为了找到当前循环内的最小值,键值对和序列分别存在tempNode和tempIndexForSmallest中。第一层循环确定当前是在排第几个数,并将内层for循环找到的最小值和首位的data[i]交换。
/**
* *****************************************************
* 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
更多推荐
已为社区贡献2条内容
所有评论(0)