JavaScript常见排序算法
Posted The Beatles
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript常见排序算法相关的知识,希望对你有一定的参考价值。
1.冒泡排序
function bubble_sort(arr) { if (arr.length <= 1) { return arr; } var len = arr.length; for (var i = 0; i < len; i++) { for (var j = 0; j < len - 1; j++) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } var arr = [3, 5, 8, 1, 2, 4, 7, 9]; var sort = bubble_sort(arr); console.log(sort);
2.快速排序
function quick_sort(arr) { if (arr.length <= 1) return arr; var pivot = Math.floor((arr.length - 1) / 2), //Math.fllor()返回一个小于或者等于给定数字的最大整数 pivotValue = arr[pivot], left = [], right = []; arr = arr.slice(0, pivot).concat(arr.slice(pivot + 1)); //concat()连接两个数组返回一个新的数组 slice()返回包含提取元素的新数组 for (var i = 0; i < arr.length; i++) { if (arr[i] < pivotValue) { left.push(arr[i]); } else { right.push(arr[i]); } } return [].concat(quick_sort(left), [pivotValue], quick_sort(right)); } var arr = [3, 8, 9, 1, 2, 6, 4, 7, 5]; var sort = quick_sort(arr); console.log(sort);
3.合并排序
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()); } } return result.concat(left).concat(right); } function merge_sort(arr) { if (arr.length <= 1) return arr; var mid = Math.floor(arr.length / 2), left = arr.slice(0, mid), right = arr.slice(mid); return merge(merge_sort(left), merge_sort(right)); } var arr = [3, 8, 9, 1, 2, 6, 4, 7, 5]; var sort = merge_sort(arr); console.log(sort);
4.选择排序
function selection_sort(arr) { for (var i = 0; i < arr.length; i++) { var min = i; for (var j = i + 1; j < arr.length; j++) { if (arr[j] < arr[min]) { min = j; } } if (min != i) { var temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } } return arr; } var arr = [3, 8, 9, 1, 2, 6, 4, 7, 5]; var sort = selection_sort(arr); console.log(sort);
5.插入排序
function insertion_sort(arr) { for (var i = 0; i < arr.length; i++) { var j = i - 1, temp = arr[i]; while (j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j]; arr[j] = temp; j--; } } return arr; } var arr = [3, 8, 9, 1, 2, 6, 4, 7, 5]; var sort = insertion_sort(arr); console.log(sort);
以上是关于JavaScript常见排序算法的主要内容,如果未能解决你的问题,请参考以下文章