Skip to content

Instantly share code, notes, and snippets.

@kevjose
Last active March 7, 2017 10:42
Show Gist options
  • Save kevjose/279e291ea13c9f6d707930d70aa825fe to your computer and use it in GitHub Desktop.
Save kevjose/279e291ea13c9f6d707930d70aa825fe to your computer and use it in GitHub Desktop.
Array.prototype.swap = function(i, j){
var temp = this[i];
this[i] = this[j];
this[j] = temp;
}
Array.prototype.bubbleSort = function(){
var swapped;
do{
swapped = false;
for(var i = 0; i < this.length; i++){
if(this[i] > this[i+1]){
this.swap(i, i+1);
swapped = true;
}
}
}while(swapped);
}
Array.prototype.selectSort = function(){
var min;
for(var i = 0; i < this.length; i++){
min = i;
for(var j= i+1; j< this.length; j++){
if(this[j] < this[min]){
min = j;
}
}
if(min !== i){
this.swap(i, min)
}
}
}
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
array.bubbleSort();
console.log(array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment