Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java代码对1到9之间的100万个整数进行排序_Java_Algorithm_Sorting - Fatal编程技术网

使用Java代码对1到9之间的100万个整数进行排序

使用Java代码对1到9之间的100万个整数进行排序,java,algorithm,sorting,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] 对于大的输入,Java的Collections.sort()使用TimSort,它在O(n log(n))上运行。 如果您想让它运行得更快,比如说线性时间,那么就应该使用基于非比较的排序算法 由于整数的范围比要排序的项数小得多,因此这是最适合的用法 是k=9(范围从1

给定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]

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

由于整数的范围比要排序的项数小得多,因此这是最适合的用法


k=9
(范围从1-9)和
N=100万
。您的运行时间将是O(k+N)

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

输入:[1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]
输出:[1,2,2,3,4,4,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] 索引01 2 3 4 5 6 7 8 9

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

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

索引2的值是2,所以我们将加上2次

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

索引4的值是2,所以我们将只加4两次

通过这种方式,可以覆盖原始数组

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]);
  }
int[]input=newint[15]{1,2,5,4,7,8,9,6,5,4,2,3,6,5,8};
int k=9;
int[]temp=新int[k+1];
for(int index=0;index
use counting sort use@khelwood我怀疑这个练习是否允许使用array.sort。这是一个常见的面试问题。另外,Arrays.sort应该是O(n logn),其中as counting sort是O(n)。为1、2…9的数量创建计数器数组。运行给定的元素,计算出有多少个元素。然后在计数器上循环,将第一个计数1s填入1,下一个计数2s填入2,以此类推