var quickSort = function(array) { if (array.length <= 1) { return array; } var middleIndex = Math.floor(array.length / 2); var middle = array.splice(middleIndex, 1)[0]; var left = []; var right = []; for (var i = 0; i < array.length; i++) { if (array[i] < middle) { left.push(array[i]); } else { right.push(array[i]); } } return quickSort(left).concat([middle], quickSort(right)); };
function selectSort(array){ var len = array.length, min; for (i=0; i < len; i++){ min = i; for (j=i+1; j < len; j++){ if (array[j] < array[min]){ min = j; } } if (i != min){ exchange(array, i, min); } } return array; } function exchange(array, p1, p2){ var temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; }
function bubbleSort(array){ var len = array.length; var i; var j; var stop; for (i = 0; i < len - 1; i++){ for (j = 0, stop = len - 1 - i; j < stop; j++){ if (array[j] > array[j + 1]){ exchange(array, j, j + 1); } } } return array; } function exchange(array, p1, p2){ var temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; }
function insertSort(array) { var len = array.length, value, i, j; for (i=0; i < len; i++) { value = array[i]; for (j=i-1; j > -1 && array[j] > value; j--) { array[j+1] = array[j]; } array[j+1] = value; } return array; }
function merge(left, right) { var result = [], left_index = 0, right_index = 0; while (left_index < left.length && right_index < right.length) { if (left[left_index] < right[right_index]) { result.push(left[left_index++]); } else { result.push(right[right_index++]); } } return result.concat(left.slice(left_index)).concat(right.slice(right_index)); } function mergeSort(array) { if (array.length < 2) { return array; } var middle = Math.floor(array.length / 2), left = array.slice(0, middle), right = array.slice(middle); return merge(mergeSort(left), mergeSort(right)); }
标签: JS冒泡排序, JS合并排序, JS快速排序, js排序方法, JS插入排序, JS选择排序
上面是“js最常见的几种排序方法介绍”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_4344.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!