2016-11-17 53 views
0

我很難理解如何將選擇排序轉換爲泛型。我已經寫了一個經典的選擇排序算法,請你幫我理解插入<T> & T轉換選擇排序爲泛型<T>,T

class Program 
{ 
    static void Main(string[] args) 
    { 
     int[] numbers = { 34, 17, 23, 35, 26, 9, 13 }; 

     //Print Array in Selection Sort 
     SelectionSort(numbers); 
     for (int i = 0; i < numbers.Length; ++i) 
     { 
      Console.WriteLine(numbers[i] + " "); 
     } 

     Console.ReadLine(); 
    } 

    public static void SelectionSort(int [] numArray) 
    { 
     for (int i = 0; i < numArray.Length -1; ++i) 
     { 
      int minElement = numArray[i]; //Hold smallest remaining int @ i = 0 
      int minLocation = i; 

      for (int j = i + 1; j < numArray.Length; ++j) 
      { 
       if (numArray[j] < minElement) 
       { 
        minElement = numArray[j]; // Update index of minElement 
        minLocation = j; 
       } 
      } 

      //Swap 
      if (minLocation != i) 
      { 
       int temp = numArray[minLocation]; 
       numArray[minLocation] = numArray[i]; 
       numArray[i] = temp; 
      } 
     } 
    } 
} 

至於我可以從我的閱讀理解,我只能走這麼遠:

public static void SelectionSort<T>(T[] numArray) : IComparable 

感謝您的幫助,您可以用選擇排序算法的剩餘部分提供。

回答

3

基本上,你想要做的是先改變簽名。由於您不再想要傳入int數組而只能使用通用數組,因此需要將參數類型更改爲T[]。對於工作,你需要做的方法一般通過將類型參數有作爲:

public static void SelectionSort<T>(T[] numArray) 

由於元素類型現在是T而不是int,則需要更換所有int s表示提到的元件T。例如:

// minElement is an element of the array, so its type is T 
T minElement = numArray[i]; 

// but the location is an index, so that stays an int 
int minLocation = i; 

一旦你這樣做,你會遇到你不能使用<操作上T編譯器的問題。這是因爲沒有關於類型T的信息表明它有訂單。所以我們在這裏做的是在T上使用泛型類型約束。我們在這裏使用IComparable<T>界面;使用它改變了方法簽名改成這樣:

public static void SelectionSort<T>(T[] numArray) 
    where T: IComparable<T> 

一旦我們有了這一點,我們可以更換一個呼叫<比較CompaterTo

if (numArray[j].CompareTo(minElement) < 0) 

而這將是所有有做的這種方法。這是完全轉換的代碼:

public static void SelectionSort<T>(T[] numArray) 
    where T: IComparable<T> 
{ 
    for (int i = 0; i < numArray.Length -1; ++i) 
    { 
     T minElement = numArray[i]; 
     int minLocation = i; 

     for (int j = i + 1; j < numArray.Length; ++j) 
     { 
      if (numArray[j].CompareTo(minElement) < 0) 
      { 
       minElement = numArray[j]; 
       minLocation = j; 
      } 
     } 

     if (minLocation != i) 
     { 
      T temp = numArray[minLocation]; 
      numArray[minLocation] = numArray[i]; 
      numArray[i] = temp; 
     } 
    } 
} 
+0

非常感謝!我無法弄清楚放置CompareTo()的位置,而且我在Swap上遇到困難 - 我沒有放置T temp。非常感謝您的幫助! –

相關問題