排序算法

2020-04-27  本文已影响0人  弹指一挥间_e5a3
  1. 递归找到最小值排序
function minIndexOf(numbers){
    var minIndex = 0;
    for(let i = 1;i < numbers.length;i++) {
        if(numbers[i] < numbers[minIndex]) {
            minIndex = i;
        }
    }
    return minIndex;
}

function sort(numbers) {
    if(numbers.length > 2) {
    let index = minIndexOf(numbers);
    let min = numbers[index];
    numbers.splice(index,1);
    return [min].concat(sort(numbers))
  }else {
   return numbers[0] < numbers[1] ? numbers : numbers.reverse();
  }  
}

2.选择排序

// 找寻数组中的最小值
function minIndexOf(numbers){
    var minIndex = 0;
    for(let i = 1;i < numbers.length;i++) {
        if(numbers[i] < numbers[minIndex]) {
            minIndex = i;
        }
    }
    return minIndex;
}
// 数组中的两个数对换位置
function swap(numbers,index,i) {
  let a = numbers[index];
  numbers[index] = numbers[i];
   numbers[i] = a;
}
function sort(numbers) {
  for(let i =0;i < numbers.length -1;i++) {
    let index = minIndexOf(numbers.slice(i)) +i;
    if(index !== i) {swap(numbers,index,i)}
  }
return numbers
}
  1. 归并排序
function mergeSort(numbers) {
  const k = numbers.length;
  if(k === 1) return numbers;
  const left= numbers.slice(0,Math.floor(k/2));
  const right = numbers.slice(Math.floor(k/2));
  return merge(mergeSort(left),mergeSort(right));
}

function merge(a,b) {
  if(a.length === 0) return b;
  if(b.length === 0) return a;
  return a[0] > b[0] ? [b[0]].concat(merge(a,b.slice(1))) : [a[0]].concat(merge(a.slice(1),b))
}

4.计数排序(哈希表)

function sort(numbers) {
  let hashTable = {},max = 0,result = [];
  for(let i = 0;i< numbers.length;i++) {
    if(!(numbers[i] in hashTable)) {
      hashTable[numbers[i]] = 1
    }else {
      hashTable[numbers[i]] += 1
    }
  if(numbers[i] > max) {
    max = numbers[i]
    }
  }
  for(let j = 0;j < max;j++){
    if(j in hashTable){
      for(let i =0;i< hashTable[j];i++){
        result.push(j)
      }
    }  
  }
return result;
}
上一篇下一篇

猜你喜欢

热点阅读