Algorithm 关于计数排序算法

Algorithm 关于计数排序算法,algorithm,analysis,Algorithm,Analysis,我读过一个计数排序算法,它是这样的: Counting Sort(A[1,..n]) //C[1,...k] is the temporary memory and k is the range of integers for i<-- 1 to k C[i]<-- 0 for j<-- 1 to n C[A[j]]<--C[A[j]]+1 for i<--2 to k C[i]<--C[i]+C[i

我读过一个计数排序算法,它是这样的:

Counting Sort(A[1,..n]) //C[1,...k] is the temporary memory and k is the range of integers
   for  i<-- 1 to k
      C[i]<-- 0
   for  j<-- 1 to n
      C[A[j]]<--C[A[j]]+1
   for  i<--2 to k
      C[i]<--C[i]+C[i-1]
   for  j<--n downto 1
      B[C[A[j]]]<--A[j]
      C[A[j]]<--C[A[j]]-1
计数排序(A[1,…n])//C[1,…k]是临时内存,k是整数的范围

对于i来说,算法似乎和我一样稳定


如果将最后一个
更改为
,则它仍然是正确的,但不会稳定。(将颠倒相等元素的顺序)。

好的,算法的简短说明:

  • for循环:使用0和大小k(整数范围)初始化C数组
  • for循环:计算整数并将数字存储在C中
  • for循环:求和值的总数减去给定值 例如:有五个1,三个2,两个3=>c[1]=5,c[2]=8,c[3]=10
  • for循环:从数组的末尾开始,将其放入B值中相应的C值,然后减小C值

  • 因为在C数组中存储不同数字的最后一个位置,所以也必须从数组的末尾开始。如果只处理整数,那么如果从j not stable开始,该算法也将是正确的

    该算法在两方面都是正确的。它也是稳定的,因为你现在有它

    如果您将
    的最后一个
    更改为您所说的,它将停止稳定


    基本上,
    C[i]=有多少个元素Yes,
    1到n
    仍然可以正确排序,但您将使用
    n到1
    所具有的稳定性

    在第二个循环
    C
    包含计算和之后,这些值正好是最终数组中每个数字的最后一个元素的指示。这就是为什么倒退能带来稳定

    您还可以获得
    1到n的稳定性:

    Counting Sort(A[1,..n]) //C[1,...k] is the temporary memory and k is the range of integers
       for  i<-- 1 to k
          C[i]<-- 0
       for  j<-- 1 to n
          C[A[j]]<--C[A[j]]+1
       last <-- C[1]
       C[1] <-- 0
       for  i<--2 to k
          tmp <-- C[i]
          C[i]<--C[i-1]+last
          last <-- tmp
       for  j<--n downto 1
          B[C[A[j]]]<--A[j]
          C[A[j]]<--C[A[j]]-1
    
    计数排序(A[1,…n])//C[1,…k]是临时内存,k是整数的范围
    
    对于你的简短解释和你的例子,我得到了全部结果。还有什么方法可以证明这个“for”算法是正确的吗?这也是稳定的。请看这个链接,我找到了它:我希望,它不会丢失格式。-该死的,是的-看我的答案,我在你的第二条评论中添加了一个例子。当然,有一种方法可以证明,对于另一个for循环,它也是正确的。但时间还早,我目前还不知道该怎么做;-)这也是稳定的。请看我找到的链接:
    C[1] = 1
    C[2] = 1
    
    C[1] = 2
    C[2] = 1
    
    Counting Sort(A[1,..n]) //C[1,...k] is the temporary memory and k is the range of integers
       for  i<-- 1 to k
          C[i]<-- 0
       for  j<-- 1 to n
          C[A[j]]<--C[A[j]]+1
       last <-- C[1]
       C[1] <-- 0
       for  i<--2 to k
          tmp <-- C[i]
          C[i]<--C[i-1]+last
          last <-- tmp
       for  j<--n downto 1
          B[C[A[j]]]<--A[j]
          C[A[j]]<--C[A[j]]-1