使用Java代码对1到9个整数进行排序,范围从1到9

时间:2014-09-25 20:55:00

标签: java algorithm sorting

给出1到9之间的100万个整数的集合。你会如何有效地对它们进行排序?

Input: [1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]  
Output: [1,2,2,3,4,4,5,5,5,6,6,7,8,8,9]

3 个答案:

答案 0 :(得分:8)

对于大输入,Java的Collections.sort()使用TimSort,它运行在 O(n log(n))上。 如果你想让它运行得更快,那就说线性时间比你应该使用非基于比较的排序算法。

由于您的整数范围远小于要排序的项目数,因此这是Counting Sort的完美用法。

成为k = 9(范围从1-9)和N = 1 million。您的运行时间为 O(k + N)

答案 1 :(得分:1)

创建10个数组(或10个数组的数组),每个数字一个,迭代输入数组并将每个数字添加到相应的数组。最后,结合所有数组。

答案 2 :(得分:1)

输入:[1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]
产出:[1,2,2,3,4,4,5,5,5,6,6,7,8,8,9]

这可以在O(k)空间的O(n)时间内解决。

由于给定的范围是9,我们可以创建一个大小为9 + 1的数组,其中每个索引都将在输入数组中存储一个数字

TempArray = [0 1 2 1 2 3 2 1 2 1] 指数0 1 2 3 4 5 6 7 8 9

您需要做的就是读取tempArray并将数据填回输入。

索引1处的值为1,因此我们只添加一个元素。

索引2处的值为2,因此我们将添加两个时间数字2。

索引3处的值为1,因此我们只会添加三次。

索引4处的

值为2,因此我们将仅添加四次 ....

以这种方式你可以覆盖原始数组。

T(O(n))的 S(O(k))的

如果您有任何疑惑,请告诉我。

这里是相同的c#代码:

int[] input = new int[15] { 1, 2, 5, 4, 7, 8, 9, 6, 5, 4, 2, 3, 6, 5, 8 };
  int k = 9;

  int[] temp = new int[k + 1];
  for (int index = 0; index < input.Length; index++)
  {
      temp[input[index]]++;
  }


  int i = 0; // used for input index
  for (int index = 0; index < temp.Length; index++)
  {
      while (temp[index]-- != 0)   // redusing count value after updating the index into input array
          input[i++] = index;
  }

  for (int index = 0; index < input.Length; index++)
  {
      Console.Write(" {0} ", input[index]);
  }
相关问题