2017-04-22 18 views
-1

作为我的一项任务的一部分,我获得了一组11个文本文件来演示各种搜索和排序功能。这些文件中的数据包括整数,浮点数和字符串。我使用了两种排序算法对字符串和整数进行排序,并希望重新使用其中的一种排序浮点数。是否有可能适应我的代码使用浮点数组作为替代整数数组?在排序算法中使用不同的数组类型

代码的算法:

public static void InsertionSort(int[] intArray){ 
    int temp, j; 
    for (int i = 1; i< intArray.Length; i++){ 
     temp = intArray[i]; 
     j = i - 1; 

     while(j >=0 && intArray[j] > temp){ 
      intArray[j+1] = intArray[j] 
      j--; 
     } 
    intArray[j+1] = temp; 
    }  
    for (int i = 0; i < intArray.Length; i++){ 
     Console.WriteLine(intArray[i]); 
    } 
} 
+1

使它[泛型方法(https://msdn.microsoft.com/en-us /library/twcad0zb.aspx)? – UnholySheep

回答

0

你可以把它的通用方法,以便通过类型参数。然而,并非所有类型都以统一的方式相媲美,所以你可以限制自己那些实现IComparable<T>

public static void InsertionSort<T>(T[] array) 
     where T : IComparable<T> 
    { 
     T temp; 
     int j; 

     for (int i = 1; i < array.Length; i++) 
     { 
      temp = array[i]; 
      j = i - 1; 

      while (j >= 0 && array[j].CompareTo(temp) > 0) 
      { 
       array[j + 1] = array[j]; 
       j--; 
      } 
      array[j + 1] = temp; 
     } 

     for (int i = 0; i < array.Length; i++) 
     { 
      Console.WriteLine(array[i]); 
     } 
    } 
+0

完美地工作。谢谢! – jcrossley

相关问题