Java冒泡排序算法实例分析(4)

int[] arr = new int[]{12,4,54,57,87,3,39,40,41,42,43,44,45,46,47} ;
        bubbleSort_up(arr);
        System.out.println("最终结果:" + Arrays.toString(arr));

结果:

待排序数组:[12, 4, 54, 57, 87, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47]
#第1次排序结果:[4, 12, 54, 57, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 87]
#第2次排序结果:[4, 12, 54, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 57, 87]
#第3次排序结果:[4, 12, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第4次排序结果:[4, 3, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第5次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第6次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#bubbleSort_up forloop count - 69
最终结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]

再来看未优化的冒泡排序:

执行:

int[] arr = new int[]{12,4,54,57,87,3,39,40,41,42,43,44,45,46,47} ;
        bubbleSort(arr);
        System.out.println("最终结果:" + Arrays.toString(arr));

结果:

待排序数组:[12, 4, 54, 57, 87, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47]
#第1次排序结果:[4, 12, 54, 57, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 87]
#第2次排序结果:[4, 12, 54, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 57, 87]
#第3次排序结果:[4, 12, 3, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第4次排序结果:[4, 3, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第5次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第6次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第7次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第8次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第9次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第10次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第11次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第12次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第13次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#第14次排序结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]
#bubbleSort forloop count - 105
最终结果:[3, 4, 12, 39, 40, 41, 42, 43, 44, 45, 46, 47, 54, 57, 87]

未优化情况下,多排序了36次。

优化后的冒泡排序方法仍然会有一轮无效排序,如果有更好的思路,欢迎留言指正。

优化版的冒泡排序,数组越长、越有序,效率越高。

以上。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/e2f5b2079f671f0f5f83ffa7ef57352f.html