还有另一种方式来优化这个冒泡排序? [英] There is another way to optimize this bubble-sort?

查看:220
本文介绍了还有另一种方式来优化这个冒泡排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code的排序使用冒泡排序算法,数字数组。

I have this code which sort a numeric array using bubble sort algorithm.

var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];

function bubbleSort(a)
{
    var swapped;
    do {
        swapped = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] < a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}

bubbleSort(a);
alert(a);

您可以在这里看到: http://jsfiddle.net/x7VpJ/

那么,它的工作原理完美的,因为你可以检查,但我想知道是否有另一种方式来优化该做用实际的方法较少的循环。我的意思是,使用的的变量。 也许omiting排序项......好吗?

Well, it works perfect as you can check, but I wondered if there is another way to optimize this to do fewer loops using the actual method. I mean, using swapped variable. Maybe omiting the sorted items... some idea?

在此先感谢。

推荐答案

下面是我一直在寻找的解决方案:

Here is the solution that I was looking for:

var a = [34, 203, 3, 746, 200, 984, 198, 764, 9, 1, 32423, 3455, 23, 4234,23];

function bubbleSort(a)
{
    var swapped;
    var n = a.length-1;
    var j = 0;
    do {
        swapped = false;
        for (var i=0; i < n; i++) {
            if (a[i] < a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
        n--;
    } while (swapped);
}

bubbleSort(a);
alert(a);

http://jsfiddle.net/x7VpJ/1/

谢谢大家的响应。

这篇关于还有另一种方式来优化这个冒泡排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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