本文介绍了冒泡排序算法 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请你告诉我这个冒泡排序算法在 JavaScript 中的实现有什么问题?

Please can you tell me what is wrong to this implementation of bubble sort algorithm in JavaScript?

for (var i=1; i<records.length; i++){
        for (var j=records.length; j<1; j--){
            if (parseInt(records[i-1]) < parseInt(records[i])){
                var temp = records[i-1];
                records[i-1] = records[i]
                records[i] = temp;
            }   
        }    
    }

推荐答案

冒泡排序的一对代码

冒泡排序不应该用于较大的数组,可以用于较小的数组,因为它很简单.

bubblesort should not be used for larger arrays, can be used for smaller ones for its simplicity.

优化方式,所有检查

const bubble_Sort = (nums) => {
  if(!Array.isArray(nums)) return -1; // --->if passed argument is not array
  if(nums.length<2) return nums; // --->if array length is one or less

    let swapped=false
     temp=0,
     count=-1,
     arrLength=0;


    do{
      count ++;
      swapped=false;
      arrLength = (nums.length-1) - count; //---> not loop through sorted items
      for(let i=0; i<=arrLength; i++){
          if(nums[i]>nums[i+1]){
            temp=nums[i+1];
            nums[i+1]=nums[i];
            nums[i]=temp;
            swapped=true;
          }
      }
    }

    while(swapped)
    return nums;
  }
  console.log(bubble_Sort([3, 0, 2, 5, -1, 4, 1]));

方法一

var a = [33, 103, 3, 726, 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);
console.log(a);

方法二

function bubbleSort(items) {
    var length = items.length;
    //Number of passes
    for (var i = 0; i < length; i++) { 
        //Notice that j < (length - i)
        for (var j = 0; j < (length - i - 1); j++) { 
            //Compare the adjacent positions
            if(items[j] > items[j+1]) {
                //Swap the numbers
                var tmp = items[j];  //Temporary variable to hold the current number
                items[j] = items[j+1]; //Replace current number with adjacent number
                items[j+1] = tmp; //Replace adjacent number with current number
            }
        }        
    }
}

方法三

function bubbleSort() {
    var numElements = this.dataStore.length;
    var temp;
    for (var outer = numElements; outer >= 2; --outer) {
        for (var inner = 0; inner <= outer-1; ++inner) {
            if (this.dataStore[inner] > this.dataStore[inner+1]) {
                swap(this.dataStore, inner, inner+1); }
        }
        console.log(this.toString()); 
    }
}

这篇关于冒泡排序算法 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 00:19