2016-11-17 3 views
0

선택 정렬을 제네릭으로 변환하는 방법을 이해하는 데 어려움이 있습니다. 고전적인 선택 정렬 알고리즘을 작성했습니다. <T> & T의 삽입을 이해하는 데 도움이 될 수 있습니까?선택 사항을 Generics로 정렬 <T>, T

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

당신이 선택 정렬 알고리즘의 나머지 제공 할 수있는 모든 도움을 주셔서 감사합니다

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; 
      } 
     } 
    } 
} 

는 지금까지 내가 내 독서에서 이해할 수있다, 나는 단지까지로 얻을 수 있습니다.

답변

3

기본적으로 서명을 먼저 변경하면됩니다. 더 이상 int 배열이지만 일반 배열은 전달하지 않으므로 매개 변수 유형을 T[]으로 변경해야합니다. 그 작동하려면, 당신은뿐만 아니라이 유형의 매개 변수를 추가하여이 방법은 일반적인해야 : 요소의 형태가 지금 T 대신 int 때문에

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

을, 당신은 언급 된 모든 int의를 교체해야 요소 에 의해 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> 인터페이스를 사용합니다. 그것은이에 메소드 서명을 변경하여 :

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

을 그리고 그 동안 무엇을이 모든 것 : 우리는 일단

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

, 우리는 CompaterTo에 전화로 < 비교를 대체 할 수 있습니다 이 방법. 다음은 완전히 변환 된 코드입니다.

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()를 어디에 두어야하는지 잘 알지 못했고 스왑에 어려움을 겪고있었습니다. 저는 T temp를 넣지 않았습니다. 도움을 주셔서 대단히 감사합니다! –