本文共 2525 字,大约阅读时间需要 8 分钟。
冒泡排序是一种简单有效的排序算法,通过反复交换相邻元素的位置,使数组逐渐变得有序。具体流程如下:
以下是冒泡排序的原始代码实现:
package bubblesort;public class sort1 { public static void main(String[] args) { int[] arr = {1, 4, 5, 2, 6, 8, 4, 5}; int end = arr.length - 1; for (; 0 <= end; end--) { for (int start = 0; start < end; start++) { if (arr[start] > arr[start + 1]) { int temp = arr[start]; arr[start] = arr[start + 1]; arr[start + 1] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }} 优化思路:如果在排序到一半时数组已经有序,后续的排序操作是浪费资源。我们可以通过在每次排序开始前判断数组是否已经有序,提前终止排序过程。
实现方案:在每次排序开始前,检查数组中是否存在相邻元素逆序。如果没有,说明数组已经有序,直接退出循环。
package bubblesort;public class sort1 { public static void main(String[] args) { int[] arr = {1, 4, 5, 2, 6, 8, 4, 5}; int end = arr.length - 1; for (; 0 <= end; end--) { boolean isSorted = true; for (int start = 0; start < end; start++) { if (arr[start] > arr[start + 1]) { int temp = arr[start]; arr[start] = arr[start + 1]; arr[start + 1] = temp; isSorted = false; } } if (isSorted) { break; } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }} 优化思路:在排序过程中,数组的后半部分可能已经局部有序。我们可以记录最后一次交换的位置,并将后续排序范围缩减到这一位置之前,从而减少不必要的比较和交换。
实现方案:在每次循环中记录最后一次交换的位置。如果后续没有交换发生,说明前面已经有序,可以提前终止排序。
package bubblesort;public class sort3 { public static void main(String[] args) { int[] arr = {1, 4, 5, 2, 6, 8, 4, 5}; int end = arr.length - 1; for (; 0 <= end; end--) { int sortIndex = 1; for (int start = 0; start < end; start++) { if (arr[start] > arr[start + 1]) { int temp = arr[start]; arr[start] = arr[start + 1]; arr[start + 1] = temp; sortIndex = start; } } end = sortIndex; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }} 冒泡排序是一种稳定的排序算法。稳定性意味着:如果两个元素相等,它们在排序后的顺序与原始顺序相同。这种特性在处理多个相同元素时尤为重要。
以上就是冒泡排序算法及其优化方案,希望对您有所帮助!如有疑问,欢迎在评论区留言。我将致力于提供高质量的技术内容,感谢您的关注与支持!
转载地址:http://nckfz.baihongyu.com/