冒泡排序
稳定,
O(n
2
), O(1)
var bubbleSort = function(arr){
for(var i=0;i < arr.length -1; i++){
for(var j=i+1;j< arr.length;j++){
if(arr[i]>arr[j]){//如果前面的数据比后面的大就交换
var temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}console.log(arr[i])
}
return arr;
}
插入排序 稳定
O(n
2
), O(1)
var insetSort =function(arr) {
var len = arr.length;
if (len <=1) {
return len;
}
for(var i = 1; i < len; i++) {
var tmp = arr[i];
for(var j = i; j > 0 && arr[j-1] > tmp; j-- ) {
arr[j] = arr[j-1];
}
arr[j] = tmp;
}
return arr;
}
快速排序 不稳定
O(n*log
2
n)
,
O(log
2
n)~O(n)
var quickSort = function(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]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
选择排序 稳定
O(n
2
), O(1)
var selectSort = function(arr) {
console.log(arr);
if(arr.length <= 1) {
return arr;
}
for(var i = 0; i < arr.length; i++) {
var tmp = i;
for(var j = i + 1; j < arr.length; j++) {
if(arr[j] < arr[tmp])
tmp = j;
}
if(i !== tmp) {
var temp = arr[i];
arr[i] = arr[tmp];
arr[tmp] = temp;
}
}
return arr;
}
归并排序 稳定
O(nlogn)
O(n)
var mergeSort = function(arr) {
var len = arr.length;
if(len <= 1)
return arr;
var index = Math.floor(len / 2);
var left = arr.slice(0, index);
var right = arr.slice(index);
return merge(mergeSort(left), mergeSort(right));
}
var merge = function(left, right) {
var arr = [];
while(left.length && right.length) {
if(left[0] < right[0]) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}
return arr.concat(left, right);
}