Skip to main content
 首页 » 编程设计

c#之为什么我的 Gnome 排序算法会导致我的系统挂起

2024年02月13日11cloudgamer

这是我的 Gnome 排序算法,由于某种原因,当我使用它时,它会导致我的系统挂起。我认为这可能与 comparer.Compare(x,y) == 1 部分有关,但不确定。

    static public void GnomeSort<T>(IList<T> list) 
    { 
        GnomeSort<T>(list, Comparer<T>.Default); 
    } 
 
    static public void GnomeSort<T>(IList<T> list, IComparer<T> comparer) 
    { 
        bool stillGoing = true; 
        while (stillGoing) 
        { 
            stillGoing = false; 
            for (int i = 1; i < list.Count; ) 
            { 
                T temp; 
                T x = list[i - 1]; 
                T y = list[i]; 
                if (comparer.Compare(x,y) == 1) 
                    i++; 
                else 
                { 
                    temp = x; 
                    x = y; 
                    y = temp; 
                    i--; 
                    if (i == 0) 
                        i = 1; 
                    stillGoing = true; 
                }  
            } 
        } 
    } 

请您参考如下方法:

您永远不会更改传入列表。所以你总是有未排序的列表

   if (comparer.Compare(x,y) > 0) 
   { 
        i++; 
   } 
   else 
   { 
       list[i-1] = y; 
       list[i] = x; 
       i--; 
       if (i == 0) 
           i = 1; 
       stillGoing = true; 
    }