码迷,mamicode.com
首页 > 编程语言 > 详细

【排序算法的JavaScript实现】

时间:2015-04-27 13:13:35      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

冒泡排序

  1. let compare = (n1, n2) => n1 - n2;
  • let bubbleSort = (arr, cmp = compare) => {
  •   for (let i = 0; i < arr.length; i++) {
  •     for (let j = i; j > 0; j--) {
  •       if (cmp(arr[j], arr[j - 1]) < 0) {
  •         [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];
  •       }
  •     }
  •   }
  •   return arr;
  • };


插入排序

  1. let insertionSort = (arr) => {
  •     for (let i = 0; i < a.length; i++) {
  •         let toCmp = arr[i];
  •         for (let j = i; j > 0 && toCmp < a[j - 1]; j--)
  •             arr[j] = a[j - 1];
  •         arr[j] = toCmp;
  •     }
  •     return arr;
  • }


选择排序

  1. var selectionSort = function (arr) {
  •   let i,m,j;
  •   for (i = -1; ++i < a.length;) {
  •     for (m = j = i; ++j < a.length;) {
  •       if (arr[m] > arr[j]) m = j;
  •     }
  •     [arr[m], arr[i]] = [arr[i], arr[m]];
  • }
  • return arr;
  • }


归并排序

  1. let mergeSort = (arr) => {
  •   if (arr.length < 2) return arr;
  •   let middle = parseInt(arr.length / 2),
  •   left = arr.slice(0, middle),
  •   right = arr.slice(middle);
  •   return merge(mergeSort(left), mergeSort(right));
  • }
  • let merge = (left, right) => {
  •   let result = [];
  •   while (left.length && right.length) {
  •     left[0] <= right[0] ?
  •     result.push(left.shift()) :
  •     result.push(right.shift());
  •   }
  •   while (left.length) result.push(left.shift());
  •   while (right.length) result.push(right.shift());
  •   return result;
  • }


快速排序

  1. let quicksort = function(arr) {
  •   if(arr.length <= 1) return arr;
  •   let pivot = Math.floor((arr.length -1)/2);
  •   let val = arr[pivot], less = [], more = [];
  •   arr.splice(pivot, 1);
  •   arr.forEach(function(e,i,a){
  •     e < val ? less.push(e) : more.push(e);
  •   });
  •   return (quicksort(less)).concat([val],quicksort(more))
  • }??


更多java,java面试题,java学习  http://techfoxbbs.com


【排序算法的JavaScript实现】

标签:

原文地址:http://blog.csdn.net/u014714340/article/details/45308757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!