简体   繁体   English

双数组的冒泡排序

[英]Bubble sort of a double array

I know the bubble sort algorithm but my question is that what is the efficient code for making this sorting.我知道冒泡排序算法,但我的问题是进行这种排序的有效代码是什么。 I have two models of this algorithm, I think both make bubble sort correctly but what is the best one of both with respect to memory space and time?!!我有这个算法的两个模型,我认为两者都正确地进行了冒泡排序,但是就存储空间和时间而言,两者中最好的一个是什么?!

Model A:型号 A:

public static void bubbleSort(double[] array){
    boolean sorted;
    for(int i = 0; i < array.length - 1; i++){
        sorted = true;
        for(int j = array.length - 1; j > i; j--){
            //swap
            if(array[j] < array[j - 1]){
                double temp = array[j - 1];
                array[j - 1] = array[j];
                array[j] = temp;
                sorted = false;
            }
        }
        if(sorted)
            break;
    }
}

Model B: B型:

static void bubbleSort(double[] list) {
    boolean changed = true;
    do {
        changed = false;
        for (int j = 0; j < list.length - 1; j++)
            if (list[j] > list[j+1]) {
                //swap list[j] wiht list[j+1]
                double temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
                changed = true;
            }
    } while (changed);
}

I tried to test both of them by a naïve way with System.currentTimeMillis() on 10000 random doubles.我尝试使用System.currentTimeMillis()以一种天真的方式在 10000 个随机双打上测试它们。

long a = System.currentTimeMillis();
bubbleSort(array);
long b = System.currentTimeMillis() - a;

The first sort is little faster.第一种要快一点。 I have tested always with random data separately.我总是分别用随机数据进行测试。

The first one in milliseconds: 179, 170, 185以毫秒为单位的第一个:179、170、185

The second one in milliseconds: 292, 241, 244第二个毫秒:292、241、244

The result is they work both same and fast.结果是它们既相同又快速。 In general in Java there is not much need to find the fastest way at all costs.一般来说,在 Java 中不需要不惜一切代价找到最快的方法。 So don't worry and use any of them.所以不要担心并使用它们中的任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM