常用排序方法 —— JavaScript 實現
阿新 • • 發佈:2018-11-03
一、氣泡排序
function bubbleSort(arr) {
var len = arr.length;
var temp;
for (var i = 0; i < len; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j+1];
arr[j+1] = arr[j];
arr[ j] = temp;
}
}
}
return arr;
}
二、選擇排序
function selectionSort(arr) {
var len = arr.length;
var min, temp;
for (var i = 0; i < len - 1; i++) {
min = arr[i];
for (var j = i + 1; j < len; j++) {
if (arr[j] < min) { //尋找最小的數
min = arr[j]; //將最小數的索引儲存
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
三、插入排序
function insertionSort(arr) {
var len = arr.length;
var preIndex, current;
for (var i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while(preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current;
}
return arr;
}
四、快速排序
function quickSort(arr, left, right) {
var len = arr.length,
partitionIndex;
if (left < right) {
partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex-1);
quickSort(arr, partitionIndex+1, right);
}
return arr;
}
function partition(arr, left ,right) { //分割槽操作
var pivot = left, //設定基準值(pivot)
index = pivot + 1;
for (var i = index; i <= right; i++) {
if (arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index-1;
}
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}