For*_*vin 5 c# sorting string list selection-sort
好的,我一直在使用这段代码对整数进行选择排序:
public void selectSort(int [] arr)
{
//pos_min is short for position of min
int pos_min,temp;
for (int i=0; i < arr.Length-1; i++)
{
pos_min = i; //set pos_min to the current index of array
for (int j=i+1; j < arr.Length; j++)
{
if (arr[j] < arr[pos_min])
{
//pos_min will keep track of the index that min is in, this is needed when a swap happens
pos_min = j;
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我想在字符串列表上运行相同的算法.
怎么可能完成?感觉真的很尴尬,就像你需要额外的循环来比较不同字符串的多个字符..?
我尝试了很多,但我无法想出任何有用的东西.:/
注意:我知道,选择排序不是很有效.这仅用于学习目的.我不是在寻找已经属于C#的替代算法或类.;)
现在您已经为整数数组实现了选择排序,您希望将解决方案概括为适用于任何类型的数组.这可以通过泛型和IComparable
界面来完成.
泛型允许我们使用类型来参数化函数.这与使用值参数化函数的方式类似.
IComparable
是一个接口,它为我们提供了一个名为CompareTo的函数,它是一个比较运算符.此运算符适用于实现IComparable
接口的所有类型,包括整数和字符串.
// Forall types A where A is a subtype of IComparable
public void selectSort<A>(A[] arr)
where A : IComparable
{
//pos_min is short for position of min
int pos_min,temp;
for (int i=0; i < arr.Length-1; i++)
{
pos_min = i; //set pos_min to the current index of array
for (int j=i+1; j < arr.Length; j++)
{
// We now use 'CompareTo' instead of '<'
if (arr[j].CompareTo(arr[pos_min]) < 0)
{
//pos_min will keep track of the index that min is in, this is needed when a swap happens
pos_min = j;
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3404 次 |
最近记录: |