有没有一种方法可以对此排序算法进行简单的更改,使其运行速度比二次时间快?

时间:2018-10-20 00:59:44

标签: sorting pseudocode

我有以下在O(n 2 )中运行的排序算法:

function sortingArray (U, n)
//S is the array and n is the size of the array
//1. First create a temp array and initialize to 0
for i = 0 to n - 1
  Temp[i] = 0
//2. This is where it gets skewed - essentially Temp is used to store indixes for the correct position of U
for i = 0 to n - 2
  for j = i + 1 to n - 1
    if U[i] <= U[j]
      Temp[j]++
    else
      Temp[i]++
//3. Now Temp has the correct "index" order so create an array S and place the elements of U into it using Temp
for i = 0 to n - 1
  S[Temp[i]] = U[i]
return S

我已经验证了几个初始的未排序数组,并且每次都能正确排序。这个家庭作业问题的范围不是废弃此算法并编写众所周知的排序算法。相反,我将确定是否可以“简单地”修改上述算法,以使时间复杂度小于n 2 。显然使二次方成为嵌套循环的原因,但是我看不到没有两个嵌套的for循环以相同方式使用Temp的方法。

0 个答案:

没有答案