Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

计数排序 #191

Open
louzhedong opened this issue Jan 7, 2020 · 0 comments
Open

计数排序 #191

louzhedong opened this issue Jan 7, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

算法名称

计数排序

实现思路

  • 使用一个额外的数组来统计每个数字出现的次数
  • 通过数组中的最大值和最小值来计算额外数组的大小
  • 遍历原数组,在额外数组中进行统计
  • 遍历额外数组,构建新的数组

算法分析

时间复杂度为O(N),但空间复杂度较高,是一种以空间换时间的算法

算法实现

function CountSort(array) {
  var length = array.length;

  var min = Number.MAX_VALUE;
  var max = Number.MIN_VALUE;

  for (var i = 0; i < length; i++) {
    if (array[i] < min) {
      min = array[i];
    }
    if (array[i] > max) {
      max = array[i];
    }
  }

  var distance = max - min;
  var countArray = [];
  for (var i = 0; i <= distance; i++) {
    countArray[i] = 0;
  }

  for (var i = 0; i < length; i++) {
    countArray[array[i] - min] += 1;
  }

  var result = [];
  for (var i = 0; i <= distance; i++) {
    for (j = 0; j < countArray[i]; j++) {
      result.push(i + min);
    }
  }

  return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant