我有问题。我想实现插入排序,但是在不同类型的数组上 - int,string和double但我不知道如何在方法中获得不同类型的参数。这是一些代码:
private static string InsertionSort(int[] array)
{
Stopwatch stopwatch = new Stopwatch();
int index, i, j;
stopwatch.Start();
for (i = 1; i < array.Length; i++)
{
index = array[i];
j = i;
while ((j > 0) && (array[j - 1] > index))
{
array[j] = array[j - 1];
j = j - 1;
}
array[j] = index;
}
stopwatch.Stop();
return stopwatch.Elapsed.ToString();
}
我尝试使用InsertionSort(dynamic []数组),但它仍然无法正常工作。
答案 0 :(得分:6)
您可以使用其他人提到的泛型,但是为了能够比较您需要添加类型实现IComparable
的约束的项目。您还需要更改代码以使用CompareTo
而不是>
运算符。
private static string InsertionSort<T>(T[] array) where T : IComparable<T>
{
Stopwatch stopwatch = new Stopwatch();
int i, j;
T index;
stopwatch.Start();
for (i = 1; i < array.Length; i++)
{
index = array[i];
j = i;
while ((j > 0) && (array[j - 1].CompareTo(index) > 0))
{
array[j] = array[j - 1];
j = j - 1;
}
array[j] = index;
}
stopwatch.Stop();
return stopwatch.Elapsed.ToString();
}
答案 1 :(得分:2)
更新
尝试使用泛型方法声明,即
private static string InsertionSort<T>(T[] array) where T : IComparable<T>
{
Stopwatch stopwatch = new Stopwatch();
T index;
int i, j;
stopwatch.Start();
for (i = 1; i < array.Length; i++)
{
index = array[i];
j = i;
while ((j > 0) && (array[j - 1].CompareTo(index) > 0))
{
array[j] = array[j - 1];
j = j - 1;
}
array[j] = index;
}
stopwatch.Stop();
return stopwatch.Elapsed.ToString();
}
用法:
int[] intArray = new int[] {5, 23, 6, 8, 3};
string intSortTime = InsertionSort<int>(intArray);
double[] doubleArray = new double[] {5.2, 23.7, 5.0, 5.1, 8,3};
string doubleSortTime = InsertionSort<double>(doubleArray );
答案 2 :(得分:1)
使用Generics,您也可以对数组和列表使用相同的代码: 请参阅以下有关通用的示例代码:
class Program
{
static void Main()
{
int[] arr = { 0, 1, 2, 3, 4 };
List<int> list = new List<int>();
for (int x = 5; x < 10; x++)
{
list.Add(x);
}
ProcessItems<int>(arr);
ProcessItems<int>(list);
}
static void ProcessItems<T>(IList<T> coll)
{
// IsReadOnly returns True for the array and False for the List.
System.Console.WriteLine
("IsReadOnly returns {0} for this collection.",
coll.IsReadOnly);
// The following statement causes a run-time exception for the
// array, but not for the List.
//coll.RemoveAt(4);
foreach (T item in coll)
{
System.Console.Write(item.ToString() + " ");
}
System.Console.WriteLine();
}
}