#Algorithms - Basic Sorting Methods @(Data Structure & Algorithm) ##数组工具
function Arr(len){
this.dataStore = new Array(len);
this.pos = 0;
this.len = len;
}
Arr.prototype = {
constructor: Arr,
setRandom: function(){
for (var i = 0; i < this.dataStore.length; i++){
this.dataStore[i] = Math.floor(Math.random() * 100);
}
},
insert: function(el){
this.dataStore[this.pos++] = el;
},
clear: function(){
this.dataStore = [];
},
display: function(){
console.log("display:");
var str = "";
for (var i = 0; i < this.dataStore.length; i++){
str += this.dataStore[i] + " ";
if (i > 0 & i % 10 === 0){
str += "\n";
}
}
console.log(str);
},
//交换
swap: function(arr,i1,i2){
var tmp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = tmp;
}
};
var arr = new Arr(5);
arr.setRandom();
arr.display();
##Bubble Sort
//bubble sort
Arr.prototype.bubbleSort = function(){
var data = this.dataStore,
i, j;
for (i = data.length - 1; i > 0; i--){
for (j = 0; j < i; j++){
if (data[j] > data[j + 1]){
this.swap(data, j, j + 1);
}
this.display();
}
}
};
arr.bubbleSort();
arr.display();
//向下冒泡
Arr.prototype.dBubbleSort = function(){
var data = this.dataStore,
i,j;
for (i = 0; i < data.length - 1; i ++){
for(j = data.length - 1; j > i; j--){
if (data[j] < data[j - 1]){
this.swap(data, j, j-1);
}
}
}
};
arr.dBubbleSort();
arr.display();
##Selection Sort
Arr.prototype.selectionSort = function(){
var data = this.dataStore,
i,j,k;
for (i = data.length - 1; i > 0; i--){
k = i;
for (j = 0; j < i; j++){
if (data[j] > data[k]){
k = j;
}
}
this.swap(data,i,k);
}
};
arr.selectionSort();
arr.display();
//sorted 子数组在低位
Arr.prototype.lSelectionSort = function(){
var data = this.dataStore,
i,j,k;
for (i = 0; i < data.length - 1; i++){
k = i;
for(j = i + 1; j < data.length; j++){
if (data[j] < data[k]){
k = j;
}
}
this.swap(data,i,k);
}
};
arr.lSelectionSort();
arr.display();
##Insertion Sort
Arr.prototype.insertionSort = function(){
var data = this.dataStore,
i, j, tmp;
for (i = 1; i < data.length; i++){
tmp = data[i];
j = i;
while (j > 0 && (data[j - 1] > tmp)){
data[j] = data[j - 1];
j--;
}
data[j] = tmp;
}
};
arr.insertionSort();
arr.display();
//使输出从高到底只需把while判断条件改成 <
//sorted子数组在高位
Arr.prototype.hInsertionSort = function(){
var data = this.dataStore,
i, j, tmp;
for (i = data.length - 2; i >= 0; i--){
tmp = data[i];
j = i;
while (j < data.length - 1 && (tmp > data[j + 1])){
data[j] = data[j + 1];
j++;
}
data[j] = tmp;
}
};
arr.hInsertionSort();
arr.display();