2015-09-02 47 views
-1

如何使用特定的邊界和左右邊界創建插入排序的方法。在C#中使用左,右邊界的Insertion sort使用左右邊界在C#中進行插入排序

public static void InsertionWorker<TYPE>(TYPE[] data, int left, int right) where TYPE : IComparable<TYPE> 
    { 
     TYPE temp; 
     for (int firstSorted = 0; firstSorted < data.Length - 1; firstSorted++) 

     for (int current = firstSorted + 1; current > 0; current--) 
     { 
      if (data[current - 1].CompareTo(data[current]) < 0) 
      { 
      temp = data[current - 1]; 
      data[current - 1] = data[current]; 
       data[current] = temp; 
      } 
      current--; 
     } 
    } 

    public static void Insertion<TYPE>(TYPE[] data) where TYPE : IComparable<TYPE> 
    { 
     InsertionWorker(data, 0, data.Length - 1); 
    } 
+2

能幫你什麼是你的問題更具體? – zed

+1

你可能要考慮使用'T'作爲你的類型參數,就像你知道的其他人一樣。 – AakashM

回答

0

實現:

class Program 
{ 
    public static void InsertionWorker<T>(T[] data, int left, int right) where T : IComparable<T> 
    { 
     for (var i = left; i < right + 1; i++) 
     { 
      T tmp = data[i]; 
      int j; 
      for (j = i - 1; j >= left && tmp.CompareTo(data[j]) < 0; j--) 
      { 
       data[j + 1] = data[j]; 

      } 
      data[j + 1] = tmp; 
     } 
    } 

    static void Main(string[] args) 
    { 
     // test data array 
     var a = new[] {234, 2, 11111, 34, 24, 23, 4, 432, 42, 423, 1, 4, 123, 124, 32, 345, 45, 3, 7, 56,9999999}; 

     // Run insertion sort by provided boundaries 
     InsertionWorker(a, 7, a.Length-1); 

     // InsertionWorker(a, 0, 8); 

     foreach (int t in a) 
     { 
      Console.WriteLine(t); 
     } 
     Console.ReadKey(); 
    } 
} 

Insertion sort

+0

此代碼示例還需要一些參數檢查。但主要思想/算法已實施。 –