# JavaScript实现排序算法

## 冒泡排序

functon bubbleSort(arr) {
for (var i = 0; i < arr.length-1; i++) {
for (var j = 0; j < arr.length-1-i; j++) {
if (arr[j] > arr[j+1]) {
// 交换位置
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
return arr;
}
}

## 选择排序

functon selectSort(arr) {
for (var i = 0; i < arr.length-1; i++) {
var min = arr[i];
for (var j = i+1; j < len; j++) {
if (arr[j] < min) {
var temp = min;
min = arr[j];
arr[j] = temp;
}
arr[i] = min;
}
}
return arr;
}

## 插入排序

function insertSort(arr) {
for (var i = 1; i < arr.length; i++) {
var key = arr[i];
for (var j = i-1; j >= 0; j--) {
if (arr[j] > key) {
arr[j + 1] = arr[j];
} else {
arr[j + 1] = key;
}
}
}
return arr;
}

## 希尔排序

function shellSort(arr, dk) {
for (var d = dk/2; d > 0; d /= 2) {
for (var j = d; j < n; j++) {
if (arr[j] < arr[j-d]) {
var temp = arr[j];
var k = j - d;
while (k >= 0 && arr[k] > temp) {
arr[k + d] = arr[k];
k -= d;
}
arr[k + d] = temp;
}
}
}
}

## 快速排序

// key为基准值序号
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
} else {
var low = [];
var high = [];
var pivotkey = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] <= pivotkey) {
low.push(arr[i]);
} else {
high.push(arr[i]);
}
}
}
return quickSort(low).concat(pivotkey, quickSort(high));
}

+ 订阅