algorithm - 如何按大小对数字进行分组

标签 algorithm sorting complexity-theory

我有 n 个不同的数字,我想将它们分成 k 组,这样第 1 组中的任何数字都小于第 2 组中的任何数字,并且任何人在第 2 组中比第 3 组中的任何人都小,依此类推,直到第 k 组(不必在每个组内对数字进行排序)。我被要求设计一个在 O(n log k) 中运行的算法,但我只能想出 O(n^2) 个。

我该怎么做?

最佳答案

您可以通过修改桶排序算法来实现此目的,下面我包含了一个 JavaScript 实现,请参阅 Github有关源代码的更多详细信息。此实现使用 16 个桶,您必须修改它以允许 k桶,你可以省略桶本身的排序。一种方法是使用 2^p buckets 其中 p 是满足 2^p < n 的最小整数.该算法将在 O(n log k)

内运行

// Copyright 2011, Tom Switzer
// Under terms of ISC License: http://www.isc.org/software/license

/**
 * Sorts an array of integers in linear time using bucket sort.
 * This gives a good speed up vs. built-in sort in new JS engines
 * (eg. V8). If a key function is given, then the result of
 * key(a[i]) is used as the integer value to sort on instead a[i].
 *
 * @param a A JavaScript array.
 * @param key A function that maps values of a to integers.
 * @return The array a.
 */
function bsort(a, key) {
  key = key || function(x) {
    return x
  };
  var len = a.length,
    buckets = [],
    i, j, b, d = 0;
  for (; d < 32; d += 4) {
    for (i = 16; i--;)
      buckets[i] = [];
    for (i = len; i--;)
      buckets[(key(a[i]) >> d) & 15].push(a[i]);
    //This implementation uses 16 buckets, you will need to modify this
    for (b = 0; b < 16; b++)
      //The next two lines sort each bucket, you can leave it out
      for (j = buckets[b].length; j--;)
        a[++i] = buckets[b][j];
  }
  return a;
}


var array = [2, 4, 1, 5, 3];

$('#result').text(bsort(array, function(x) {
  return x
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

关于algorithm - 如何按大小对数字进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33474142/

相关文章:

java - 根据整数值对对象进行排序

algorithm - CLRS 的这段话是什么意思?

algorithm - 如何计算该算法的最坏情况分析?

algorithm - 如何将多项式变换到另一个坐标系?

c - 列出所有排列的代码的时间复杂度?

python - 如何编写池化算法以提高实验室工作效率?

algorithm - 将一个非常简单的 O(n^3) 算法优化为 O(n^2) 算法。

algorithm - 如何检查给定数字 N, N^2 是否可以表示为两个非零整数的平方和?

c++ - 带内部while循环的while循环:O(n)或O(n ^ 2)?

java - 相等元素在插入排序算法中是否保留它们的顺序?