BubbleSort实施 [英] BubbleSort Implementation

查看:143
本文介绍了BubbleSort实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现冒泡排序,但我不确定它是否正确。如果你可以看一看,如果它是一个泡沫排序,可以更好地完成,请不要害羞。以下是代码:

I tried to make an implementation of bubble sort, but I am not sure whether it is correct or not. If you can give it a look and if it is a bubble sort and can be done in better way please don't be shy. Here is the code:

package Exercises;

import java.util.*;

public class BubbleSort_6_18 
{
    public static void main(String[] args) 
    {
        Random generator = new Random();

        int[] list = new int[11];
        for(int i=0; i<list.length; i++)
        {
            list[i] = generator.nextInt(10);
        }

        System.out.println("Original Random array: ");
        printArray(list);

        bubbleSort(list);

        System.out.println("\nAfter bubble sort: ");
        printArray(list);
    }

    public static void bubbleSort(int[] list)
    {
        for(int i=0; i<list.length; i++)
        {
            for(int j=i + 1; j<list.length; j++)
            {
                if(list[i] > list[j])
                {
                    int temp = list[i];
                    list[i] = list[j];
                    list[j] = temp;
                }
            }

        }
    }

    public static void printArray(int[] list)
    {
        for(int i=0; i<list.length; i++)
        {
            System.out.print(list[i] + ", ");
        }
    }
}


推荐答案

这是冒泡排序的calssical实现,似乎没问题。有几个优化可以完成,但总体思路是一样的。以下是一些想法:

This is the calssical implementation for bubble sort and it seems to be OK. There are several optimizations that can be done, but the overall idea is the same. Here are some ideas:


  • 如果在内循环中没有执行交换时存在外循环的迭代,则中断,否使用继续

  • 在外循环的每次迭代中交换内部循环的方向 - 从左到右进行一次,然后从右到左进行一次(这有助于避免元素缓慢移动)向右端)。

这篇关于BubbleSort实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆