我有以下在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
的方法。