2016-07-10 208 views
0

我在做,有一个功能名称字母顺序排序的程序,我很容易使用的Array.Sort()和它的工作,但我需要排序功能的算法,帮助我理解功能更加字符串进行排序按字母顺序算法的c#

+0

您所描述的排序方法是基于字母顺序。想想,你有什么办法比较不同的字母吗?一旦你做了,它就是一个简单的排序算法。 –

+0

我不确定使用哪种方法。但是我知道的一个在这里有描述。我不是说这是最有效的:https://en.m.wikipedia.org/wiki/Bubble_sort –

+2

这闻起来像家庭作业对我说:【如何问功课问题](http://meta.stackexchange.com/A/10812)可能会提供一些帮助......最重要的一点感**作出诚信首先尝试自行解决问题** – TemporalWolf

回答

1

这里是Array.cs:http://www.dotnetframework.org/default.aspx/DotNET/DotNET/[email protected]/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/[email protected]/2/[email protected] 有排序方法

他们使用异常的快速排序 - 他们检查,如果一切正常,他们召唤这样的:

internal void QuickSort(int left, int right) { 
      // Can use the much faster jit helpers for array access. 
      do { 
       int i = left; 
       int j = right; 

       // pre-sort the low, middle (pivot), and high values in place. 
       // this improves performance in the face of already sorted data, or 
       // data that is made up of multiple sorted runs appended together. 
       int middle = GetMedian(i, j); 
       SwapIfGreaterWithItems(i, middle); // swap the low with the mid point 
       SwapIfGreaterWithItems(i, j);  // swap the low with the high 
       SwapIfGreaterWithItems(middle, j); // swap the middle with the high 

       Object x = keys[middle]; 
       do { 
        // Add a try block here to detect IComparers (or their 
        // underlying IComparables, etc) that are bogus. 
        try { 
         while (comparer.Compare(keys[i], x) < 0) i++; 
         while (comparer.Compare(x, keys[j]) < 0) j--; 
        } 
        catch (IndexOutOfRangeException) { 
         throw new ArgumentException(Environment.GetResourceString("Arg_BogusIComparer", x, x.GetType().Name, comparer)); 
        } 
        catch (Exception e) { 
         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e); 
        } 
        catch { 
         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed")); 
        } 
        BCLDebug.Assert(i>=left && j<=right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?"); 
        if (i > j) break; 
        if (i < j) { 
         Object key = keys[i]; 
         keys[i] = keys[j]; 
         keys[j] = key; 
         if (items != null) { 
          Object item = items[i]; 
          items[i] = items[j]; 
          items[j] = item; 
         } 
        } 
        i++; 
        j--; 
       } while (i <= j); 
       if (j - left <= right - i) { 
        if (left < j) QuickSort(left, j); 
        left = i; 
       } 
       else { 
        if (i < right) QuickSort(i, right); 
        right = j; 
       } 
      } while (left < right); 
     } 
    } 

更多信息关于它:https://en.wikipedia.org/wiki/Quicksort

+0

干净的答案,很好的工作。 –