轻量级前端框架助力开发者提升项目效率与性能
537
2022-11-05
冒泡排序算法的优化实现
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]
对比优化前与优化后,比较的次数减少了,提高了代码的性能
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~