algorithm

/*
Created by Administrator on 2016/9/5.
/
window.onload = function () {
var a = [1,5,8,3,5,7,2,8,9.5,10,7,12,7];
//var bubble = new BubbleSort(a);
//console.log(bubble.sort());

//console.log(quickSort(a)) ;

var choose = new ChooseSort(a);
console.log(choose.sort());
}

/冒泡排序算法/
function BubbleSort(arr){
this.arr = arr;
this.length = this.arr.length;
}

BubbleSort.prototype.swap = function(a,b){

var temp = this.arr[a];
this.arr[a] = this.arr[b];
this.arr[b] = temp;
}
BubbleSort.prototype.sort = function(){
for(var i = 0;i<this.length-1;i++){
for(var j = 0;j<this.length-i-1;j++){
if(this.arr[j]>this.arr[j+1]){
this.swap(j,j+1);
console.log(“change “+this.arr[j]+“ and “+this.arr[j+1]);
}
}
}
return this.arr;
}

/快速排序算法/
var quickSort = function(arr) {
console.log(“—————“);
console.log(arr);
if (arr.length <= 1) { return arr; }
var pivotIndex = Math.floor(arr.length / 2);
var pivot = arr.splice(pivotIndex, 1)[0];
var left = [];
var right = [];
for (var i = 0; i < arr.length; i++){
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
console.log(“—————“);
console.log(pivot);
console.log(arr);
console.log(left);
console.log(right);
}

return quickSort(left).concat([pivot], quickSort(right));
};

/选择排序/
function ChooseSort(arr){
this.arr = arr;
this.length = this.arr.length;
}

ChooseSort.prototype.swap = function(a,b){
var tmp = this.arr[a];
this.arr[a] = this.arr[b];
this.arr[b] = tmp;
}

ChooseSort.prototype.sort = function(){

//哇咔咔经测试,j=i+1是木有问题的!
for(var i = 0;i<this.length-1;i++){
for(var j = i+1;j<this.length;j++){
if(this.arr[i]>this.arr[j]){
this.swap(i,j);
}
}
}
return this.arr;
}


/插入排序/
function InsertSort(arr){
this.arr = arr;
this.length = this.arr.length;
}

InsertSort.prototype.sort = function(){
var i = 0;
for(i=0;i<this.length-1;i++){

var temp = this.arr[i+1];
var j = i;
/console.log(‘i:’+i)
console.log(‘j:’+j)
console.log(‘arr[j]:’+this.arr[j])
console.log(‘temp:’+temp)
console.log(this.arr)/
while(j>=0&&this.arr[j]>temp){
this.arr[j+1] = this.arr[j];
/console.log(this.arr[j])
console.log(this.arr)/
j
}
this.arr[j+1]=temp;
}
return this.arr;
}

var insertSort = new InsertSort([1,3,7,2,9,2,76,2,7,8]);
console.log(insertSort.sort())

/再写一遍插入算法*/
function InsertSortn (arr){
this.arr = arr;
this.length = this.arr.length;
}
InsertSortn.prototype.sort = function(){
for(var i =1;i<this.length;i++){
var temp = this.arr[i];
var j = i;
while (j>0&&this.arr[j-1]>temp){
this.arr[j] = this.arr[j-1];
j–;
}
this.arr[j] = temp;
}
return this.arr;
}

var insert = new InsertSortn([4,7,2,9,4,7,0,2,5,8])
console.log(insert.sort())