Javascript Array bubble_sort()

Description

Javascript Array bubble_sort()


load('helpers.js')

Array.prototype.bubble_sort = function() {
  var sorted = false
  var passes = 0//w ww .  j ava 2  s  .  c o  m
  var n = 0
  while(!sorted) {
    sorted = true
    for(var i = 1; i < this.length; i++) {
      if(this[i] < this[i-1]) {
        this.swap(i, i-1)
        sorted = false
      }
      n++
    }
    passes++
    print('  After pass '+passes+', n = '+n+', items = '+this)
  }
}

var cases = {
  sorted: range(1, 10),
  random: range(1, 10).randomize(),
  reversed: range(1, 10).reverse()
}

for(var c in cases) {
  print(c+' case')
  cases[c].bubble_sort()
  print('')
}

Javascript Array bubble_sort()


Array.prototype.bubble_sort = function() {
  var sorted = false;
  var tmp/* www. j a  v  a  2 s  .c om*/
  while (!sorted) {
    sorted = true;
    for (i=0; i < this.length; i++) {
      for (j=1; j < this.length; j++) {
        if (this[j - 1] > this[j]) {
        tmp = this[j];
        this[j] = this[j-1];
        this[j-1] = tmp;
        sorted = false;
        }
      }
    }
  }
}

var substrings = function(str){
  result = []
  for (i =0; i<str.length; i++){
    for (j = i+1; j<=str.length; j++){
      result.push(str.slice(i,j));
    }
  }
  return result;
}


console.log(substrings("cat"));

Javascript Array bubble_sort()


Array.prototype.bubble_sort = function () {
  var dup = this.slice(0);

  for (var x = dup.length - 1; x >= 0; x--) {
    for (var y = 0; y < dup.length; y++) {
      if (dup[y] > dup[y + 1]) {
        temp = dup[y + 1];//from  w  w  w . ja  v  a  2s .c o m
        dup[y + 1] = dup[y];
        dup[y] = temp;
      }
    }
  }

  return dup;
};

Javascript Array bubble_sort()


var arr = [];//from  w ww  .java  2  s  .c  o  m
for (var i = 0; i < 1000; i++) {
  arr.push(Math.floor(Math.random() * 101)); //push random number 0 - 100
}

/**
 * Array - bubble numberic sort
 *
 * @return {Array}  sort will return sorted numberic array
 */
Array.prototype.bubble_sort = function(){
  var a = this.valueOf();

  for (var i = 0; i < a.length; i++) {
    for (var j = 0; j < a.length - 1; j++) {
      if (a[j + 1] < a[j]) {
        var swap = a[j];
        a[j] = a[j + 1];
        a[j+1] = swap;
      }
    }
  }

  return a;
}



console.time("watcher");

console.log(arr);

var arr = arr.bubble_sort();

console.log(arr);

console.timeEnd("watcher");



PreviousNext

Related