JavaScipt 排序算法

Note: 请使用javascript 1.7 及以上版本测试

1. 冒泡排序

<script type="application/javascript;version=1.7">
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]];

      }
      console.log(arr);
    }
  }
}

let unsortarr = [9, 3, 5, 1, 7];
console.log("begin: " + unsortarr);
let sortarr = bubbleSort(unsortarr);
console.log("end: " + unsortarr);
</script>

2. 插入排序

<script type="application/javascript;version=1.7">
let insertionSort = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    let toCmp = arr[i];
    let j = i;
    for (; j > 0 && toCmp < arr[j - 1]; j--)
      arr[j] = arr[j - 1];
    arr[j] = toCmp;
    console.log(arr);
  }
  return arr;
}

let sortFunc = insertionSort;

let unsortarr = [9, 3, 5, 1, 7];
console.log("begin: " + unsortarr);
let sortarr = sortFunc(unsortarr);
console.log("end: " + unsortarr);
</script>

3. 选择排序

<script type="application/javascript;version=1.7">
let selectionSort = (arr) => {
  let i, m, j;
  for (i = -1; ++i < arr.length;) {
    for ( m = j = i; ++j < arr.length;) {
      if (arr[m] > arr[j]) m = j;
    }
    [arr[m], arr[i]] = [arr[i], arr[m]];
    console.log(arr);
  }
  return arr;
}

let sortFunc = selectionSort;

let unsortarr = [9, 3, 5, 1, 7];
console.log("begin: " + unsortarr);
let sortarr = sortFunc(unsortarr);
console.log("end: " + unsortarr);
</script>

4. 归并排序

<script type="application/javascript;version=1.7">
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());

  console.log(result);
  return result;
}

let sortFunc = mergeSort;

let unsortarr = [9, 3, 5, 1, 7];
console.log("begin: " + unsortarr);
let sortarr = sortFunc(unsortarr);
console.log("end: " + sortarr);
</script>

5. 快速排序

<script type="application/javascript;version=1.7">
let selectionSort = (arr) => {
  let i, m, j;
  for (i = -1; ++i < arr.length;) {
    for ( m = j = i; ++j < arr.length;) {
      if (arr[m] > arr[j]) m = j;
    }
    [arr[m], arr[i]] = [arr[i], arr[m]];
    console.log(arr);
  }
  return arr;
}

let sortFunc = selectionSort;

let unsortarr = [9, 3, 5, 1, 7];
console.log("begin: " + unsortarr);
let sortarr = sortFunc(unsortarr);
console.log("end: " + unsortarr);
</script>

你可能感兴趣的:(JavaScript,排序算法)