当前位置 : 主页 > 编程语言 > java >

冒泡排序算法的优化实现

来源:互联网 收集:自由互联 发布时间:2022-07-04
package com . yqq . app11 ; import java . util . Arrays ; /** * @Author yqq * @Date 2021/11/20 16:45 * @Version 1.0 */ public class TestBubbleSort { public static void main ( String [] args ) { int [] nums = new int []{ 1 , 3 , 5 , 4 , 2 ,
package com.yqq.app11;

import java.util.Arrays;

/**
* @Author yqq
* @Date 2021/11/20 16:45
* @Version 1.0
*/
public class TestBubbleSort {
public static void main(String[] args) {
int[] nums = new int[]{1,3,5,4,2,7,6,9,8,10,15,12,14,13,11};
System.out.println("原始顺序:"+ Arrays.toString(nums));
//冒泡排序算法
bubbleSort(nums);
//优化后的冒泡排序
betterBubbleSort(nums);
}

private static void bubbleSort(int[] nums) {
int temp;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length-1-i; j++) {
if(nums[j] > nums[j+1]){
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
System.out.println(i+1+"排序后:"+Arrays.toString(nums));
}
}
//优化后的冒泡排序
private static void betterBubbleSort(int[] nums) {
int temp;
for (int i = 0; i < nums.length; i++) {
//定义一个布尔类型的变量,标记数组是否已达到有序状态
boolean flag = true;
for (int j = 0; j < nums.length-1-i; j++) {
if(nums[j] > nums[j+1]){
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
//本趟发生了交换,表明该数组在本趟处于无序状态,需要继续比较;
flag = false;
}
}
if(flag)
break;
System.out.println(i+1+"优化排序后:"+Arrays.toString(nums));
}
}
}原始顺序:[1, 3, 5, 4, 2, 7, 6, 9, 8, 10, 15, 12, 14, 13, 11]
1排序后:[1, 3, 4, 2, 5, 6, 7, 8, 9, 10, 12, 14, 13, 11, 15]
2排序后:[1, 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 13, 11, 14, 15]
3排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11, 13, 14, 15]
4排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
5排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
6排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
7排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
8排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
9排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
10排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
11排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
12排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
13排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
14排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
15排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]原始顺序:[1, 3, 5, 4, 2, 7, 6, 9, 8, 10, 15, 12, 14, 13, 11]
1优化排序后:[1, 3, 4, 2, 5, 6, 7, 8, 9, 10, 12, 14, 13, 11, 15]
2优化排序后:[1, 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 13, 11, 14, 15]
3优化排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11, 13, 14, 15]
4优化排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

对比优化前与优化后,比较的次数减少了,提高了代码的性能


网友评论