①插入排序—insertion sort
//Insertion Sorting
arr = [53,27,36,15,2,42];
function insertionSort(arr){
var copy,len,temp;
copy = arr.slice(0);
len = copy.length;
for(var i = 1;i < len;i++){
temp = copy[i];
var j = i -1;
while(j >= 0 && copy[j] > temp){
copy[j+1] = copy[j];
j--;
}
copy[j+1] = temp;
}
return copy;
}
insertionSort(arr);//[2, 15, 27, 36, 42, 53]
②希尔排序—shell sort
//shell Sorting [insertionSort + gap]
arr = [53,27,36,15,2,42];
function shellSort(arr){
var copy,len,gap;
copy = arr.slice(0);
len = copy.length;
gap = Math.floor(len / 2);
//easy to lose
while(gap !== 0){
for(var i = gap;i < len;i++){
var j = i - gap;
var temp = copy[i];
while(j >= 0 && copy[j] > temp){
copy[j + gap] = copy[j];
j = j -gap;
}
copy[j + gap] = temp;
}
gap = Math.floor(gap / 2);
}
return copy;
}
shellSort(arr);//[2, 15, 27, 36, 42, 53]
③冒泡排序—bubble sort
//Bubble Sorting
arr = [53,27,36,15,2,42];
function bubbleSort(arr){
var copy,len;
copy = arr.slice(0);
len = copy.length;
for(var i = 0;i < len;i++){
var temp = copy[i];
for(var j = len-i-1;j < len;j++){
if(copy[j] > copy[j+1]){
temp = copy[j+1];
copy[j+1] = copy[j];
copy[j] = temp;
}
}
}
return copy;
}
bubbleSort(arr);//[2, 15, 27, 36, 42, 53]
④快速排序—quick sort
//Quick Sorting
arr = [53,27,36,15,2,42];
function quickSort(arr){
var copy,pivotIndex,pivot;
copy = arr.slice(0);
//copy.length
if(copy.length <= 1) return copy;
pivotIndex = Math.floor(copy.length / 2);
pivot = copy.splice(pivotIndex,1)[0];
var left = [];
var right = [];
for(var i = 0;i < copy.length;i++){
if(copy[i] < pivot){
left.push(copy[i]);
}else{
right.push(copy[i]);
}
}
return quickSort(left).concat(pivot,quickSort(right));
}
quickSort(arr);//[2, 15, 27, 36, 42, 53]
⑤选择排序—selection sort
//Selection Sorting
arr = [53,27,36,15,2,42];
function selectionSort(arr){
var copy,len,minIndex,temp;
copy = arr.slice(0);
len = copy.length;
for(var i = 0;i < len-1;i++){
minIndex = i;
for(var j = i+1;j < len;j++){
if(copy[minIndex] > copy[j]){
minIndex = j;
}
}
temp = copy[i];
copy[i] = copy[minIndex];
copy[minIndex] = temp;
}
return copy;
}
selectionSort(arr);//[2, 15, 27, 36, 42, 53]
⑥归并排序—merge sort
//Merge Sorting
arr = [53,27,36,15,2,42];
function mergeSort(arr){
if(arr.length < 2) return arr;
var middle = Math.floor(arr.length / 2),
left = arr.slice(0,middle),
right = arr.slice(middle);
return merge(mergeSort(left),mergeSort(right));
}
function merge(left,right){
var result = [];
while(left.length && right.length){
if(left[0] < right[0]){
result.push(left.shift());
}else{
result.push(right.shift());
}
}
while(left.length){
result.push(left.shift());
}
while(right.length){
result.push(right.shift());
}
return result;
}
mergeSort(arr);//[2, 15, 27, 36, 42, 53]
参考博客:
【JS家的排序算法】:http://www.jianshu.com/p/1b4068ccd505
【基本算法学习(一)之希尔排序(JS)】:https://segmentfault.com/a/1190000006950201
gitHub地址【可自行下载修改测试】:https://github.com/yycer/share