JavaScript BubbleSort,如何提高其效率? [英] JavaScript BubbleSort, how to improve its efficiency?

查看:58
本文介绍了JavaScript BubbleSort,如何提高其效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有与此类似的Bubblesort例程。我需要通过在对数组排序或对数组进行排序时停止循环来提高效率。

Have a bubblesort routine similar to this. I need to make it more efficient by stopping the loop when the array is sorted or if the array is already sorted.

function sortNumbers(listbox) {
  var x, y, holder;
  // The Bubble Sort method.
  for(x = 0; x < ranarray.length; x++) {
    for(y = 0; y < (ranarray.length-1); y++) {
      if(ranarray[y] > ranarray[y+1]) {
        holder = ranarray[y+1];
        ranarray[y+1] = ranarray[y];
        ranarray[y] = holder;
      }
    }
  }


推荐答案

在进入内部循环之前,创建一个布尔值以检查内部循环内部是否发生了交换。当没有交换时,对数组进行排序。

Before enter the inner loop, create a boolean to check if a swap occured inside the inner loop. When the there is no swap the array is sorted.

function sortNumbers(listbox) { 
  var x, y, holder; 
  // The Bubble Sort method. 
  for(x = 0; x < ranarray.length; x++) { 
    var swapOccured = false;
    for(y = 0; y < (ranarray.length-1); y++) { 
      if(ranarray[y] > ranarray[y+1]) { 
        holder = ranarray[y+1]; 
        ranarray[y+1] = ranarray[y]; 
        ranarray[y] = holder; 
        swapOccured = true;
      } 
    }
    if (!swapOccured) break; 
  } 

这篇关于JavaScript BubbleSort,如何提高其效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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