12

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;
            }   
        }    
    }
kostas trichas
  • 2,733
  • 6
  • 27
  • 35
  • 4
    This might work better if you tell ***us*** what the ***problem*** is with it, and then we might be able to tell your how to fix it. – Matt Sep 21 '11 at 15:33

7 Answers7

37

Couple of codes for bubble sort

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

Optimized way, with all Checks

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]));

Method 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);

Method 2

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
            }
        }        
    }
}

Method 3

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()); 
    }
}
Ignatius Andrew
  • 7,434
  • 3
  • 51
  • 51
  • 1
    Method 3 is error & partly codes! `this.dataStore.length` what's that mean ?[error codes](https://repl.it/Ev0O/1) – xgqfrms Dec 22 '16 at 08:27
  • In Method 1 , after each phase of swapping , bigger numbers always bubbles to right , so in the second phase , we can ignore the the last element , similarly after each phase we can reduce the size the array to be looked by 1 . This will reduce no of comparisons: – Bhupendra Feb 02 '19 at 08:07
  • `function bubbleSort(a) { var swapped, len = a.length; do { swapped = false; for (var i=0; i < len; i++) { if (a[i] > a[i+1]) { var temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; swapped = true; } } len-- } while (swapped); } bubbleSort(a);` – Bhupendra Feb 02 '19 at 08:08
  • Optimized way rejects TypedArray (would return -1) although the algo would work with a TypedArray. – Banane Jun 10 '20 at 13:58
  • In the Optimized solution, it should be `i – Hao Chang Jan 23 '21 at 13:51
4
for (var j=records.length; j<1; j--){

Shouldn't that be

for (var j=records.length; j>1; j--){
davbryn
  • 7,130
  • 2
  • 23
  • 46
  • i think it should be (records.length - 1) as the index start from 0 – Ujjwal Manandhar Sep 21 '11 at 15:34
  • 1
    But j isn't used as an index into an array; rather it is used as a counter – davbryn Sep 21 '11 at 15:36
  • is that really a bubble sort ? how will that work ?? – Ujjwal Manandhar Sep 21 '11 at 15:41
  • It won't bubble sort at the moment - it will just keep swapping the i and (i - 1)th element. I was just pointing out the obvious problem with his code (the reason the inner loop wasn't being entered). – davbryn Sep 21 '11 at 15:46
  • yeah i was pointing that too :) – Ujjwal Manandhar Sep 21 '11 at 15:47
  • Yes, it is. Bubble sort - exchange neihgbour items if they are not in correct order. For array with length N you need to repeat this N-1 times. There are a lot of optimization/modifications of it. The best is http://en.wikipedia.org/wiki/Shell_sort Shell sort – varela Sep 21 '11 at 15:48
  • In its broken state it wasn't a bubble sort is what I meant. He wasn't indexing his records array with the correct variable. It looked like a bit of a 'homework' question so I provided the syntax correction in the hope it might help him to debug it – davbryn Sep 21 '11 at 15:53
3

A simple implementation in ES6 JavaScript will be

    function BubbleSort(arr) {
      const sortedArray = Array.from(arr);
      let swap;
      do {
        swap = false;
        for (let i = 1; i < sortedArray.length; ++i) {
          if (sortedArray[i - 1] > sortedArray[i]) {
            [sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]];
            swap = true;
          }
        }
      } while (swap)
      return sortedArray;
    }
console.log(BubbleSort([3, 12, 9, 5]));
Collin
  • 202
  • 3
  • 7
1

My solution:

  function bubbleSort(A){
  var swapped,
      len = arr.length;

  if(len === 1) return;

  do {
    swapped = false;
    for(var i=1;i<len;i++) {
      if(A[i-1] > A[i]) {   
        var b = A[i];
        A[i] = A[i-1];
        A[i-1] = b;
        swapped = true;
      }   
    }

  }
  while(swapped)  
}

var arr = [1, 6, 9, 5, 3, 4, 2, 12, 4567, 5, 34];
bubbleSort(arr);
document.write(arr);
Andrej Kaurin
  • 11,462
  • 13
  • 44
  • 51
1

you should use j instead of i in the second loop, and don't forget to change the j<1 to j>1

Mansuro
  • 4,410
  • 4
  • 33
  • 74
  • Well thank you, i think i use J instead of I – kostas trichas Sep 21 '11 at 15:42
  • 1
    `if (parseInt(records[i-1]) < parseInt(records[i])){ var temp = records[i-1]; records[i-1] = records[i] records[i] = temp;` that's i there – Mansuro Sep 21 '11 at 15:44
  • Yes you are right, but then i get: TypeError: records[j] is undefined – kostas trichas Sep 21 '11 at 15:46
  • that's because you are trying to access records[records.length], which doesn't exist in this array, if you want to start the for loop from the end, you have to start with records.length-1 `for (var j=records.length-1; j>0; j--) ` – Mansuro Sep 21 '11 at 15:59
1

I believe that in a bubble sort, once the i loop has completed an iteration, then the i'th element is now in its correct position. That means that you should write the j loop as

for (var j = i + 1; j < records.length; j++)

Otherwise your bubble sort will be (even more) inefficient.

James
  • 18,446
  • 2
  • 23
  • 39
-1

the second for loop is coded wrong it should be

for (var i=0; i<records.length; i++){
    for (var j=0; j<records.length; j++){
        if (parseInt(records[i]) > parseInt(records[j])){
            var temp = records[i];
            records[i] = records[j];
            records[j] = temp;
        }   
    }    
}
Ujjwal Manandhar
  • 2,158
  • 16
  • 20
  • It is better to nest your `for` loop inside a `while` loop and establish a predicate for looping. The code above will continue looping and looping, till it ends... even once the list elements have already been placed in order. – shmuli Sep 25 '15 at 20:21
  • I think your code works O(n2) when best case also at place. it costly to have like this code. according to this situation its not quite well. stick to the complexity also – Sahan Dissanayaka Feb 19 '20 at 11:56