Javascript Array myBubbleSort()

Description

Javascript Array myBubbleSort()


Array.prototype.myBubbleSort = function() {
  var sorted = false;

  while (!sorted) {
    sorted = true;/* w ww .j  av a2s .  c om*/
    for (var i=0; i < this.length - 1; i++ ){
      if (this[i] > this[i + 1]) {
        var x = this[i];
        var y = this[i + 1];
        this[i+1] = x;
        this[i] = y;
        sorted = false
      }
    }
  }
  return this;
};

Javascript Array myBubbleSort()

Array.prototype.myBubbleSort = function() {
  var unsorted = true;
  while (unsorted){
    unsorted = false;//from  w w w.j  a v a2 s  . c  o m
    for (var i = 0; i < this.length - 1; i++) {
      if (this[i] > this[i + 1]) {
        var movingVal = this[i];
        this[i] = this[i + 1];
        this[i + 1] = movingVal;
        unsorted = true;
      }
    }
  }
  return this;
};

Javascript Array myBubbleSort()

function myBubbleSort(arr) {
  var length = arr.length;
  for (var i = 0; i < length; i++) {
    for (var j = 0; j < (length - i - 1); j++) {
      if(arr[j] > arr[j+1]) {
        var tmp = arr[j];
        arr[j] = arr[j+1];/* ww w .jav a 2  s .co m*/
        arr[j+1] = tmp;
      }
    }
  }
  return arr;
}

Array.prototype.myBubbleSort = function () {
  var length = this.length;
  for (var i = 0; i < length; i++) {
    for (var j = 0; j < (length - i - 1); j++) {
      if(this[j] > this[j+1]) {
        var tmp = this[j];
        this[j] = this[j+1];
        this[j+1] = tmp;
      }
    }
  }
  return this;
};





// module.exports = myBubbleSort;

Javascript Array myBubbleSort()

Array.prototype.myBubbleSort = function () {
  let sorted = false;
  while (!sorted) {
    sorted = true;/*from  ww w  . j  a v  a  2  s. c  o m*/
    for (let i = 0; i < this.length - 1; i++) {
      let j = i + 1;
      if (this[i] > this[j]) {
        this[j] = [this[i], this[i] = this[j]][0];
        sorted = false;
      }
    }
  }
  return this;
};

// console.log([4,2,6,4,78,7,4].myBubbleSort());

String.prototype.mySubString = function () {
  let substrings = [];
  for (let i = 0; i < this.length; i++) {
    for (let j = i + 1; j <= this.length; j++) {
      substrings.push(this.slice(i, j));
    }
  }
  return substrings;
};

// console.log("cat".mySubString());



PreviousNext

Related