日撸java_day45

日撸java_day45注意无论向前向后冒泡时候 每一轮确定一个位置 当某一轮没有发生交换 说明已经有序 退出循环即可

大家好,欢迎来到IT知识分享网。

第 45 天: 冒泡排序

可以向后冒,也可以向前冒

 / * Bubble sort. */ public void bubbleSort() { boolean tempSwapped; DataNode tempNode; for (int i = 0; i < length; i++) { tempSwapped = false; for (int j = length - 1; j > i; j--) { if (data[j].key < data[j - 1].key) { tempSwapped = true; tempNode = data[j]; data[j] = data[j - 1]; data[j - 1] = tempNode; }// Of if }//Of for j if (!tempSwapped) { System.out.println("Premature "); break; }// Of if System.out.println("Round " + (i+1)); System.out.println(this); }// Of for i }// Of bubbleSort / * Test unit. */ public static void bubbleSortTest() { int[] tempUnsortedKeys = {1, 3, 6, 10, 7, 5, 9}; String[] tempContents = {"if", "then", "else", "switch", "case", "for", "while"}; DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents); System.out.println(tempDataArray); tempDataArray.bubbleSort(); System.out.println("Result\r\n" + tempDataArray); }// Of bubbleSortTest

日撸java_day45

 注意无论向前向后冒泡时候,每一轮确定一个位置,当某一轮没有发生交换,说明已经有序,退出循环即可。相邻两个比较的时候,注意不要越界。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/102986.html

(0)
上一篇 2026-02-20 19:21
下一篇 2026-02-21 18:34

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信