C# 带字符串的选择排序
好的,我一直在用这段代码对整数进行选择排序:C# 带字符串的选择排序,c#,string,list,sorting,selection-sort,C#,String,List,Sorting,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
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;
}
}
}
public void selectSort(int[]arr)
{
//pos_min是min位置的缩写
内部位置最低温度;
对于(int i=0;i
但是现在我想在字符串列表上运行相同的算法。如何才能做到这一点?这感觉非常尴尬,您需要额外的循环来比较不同字符串的多个字符。
我做了很多尝试,但都没有找到有用的方法。:/ 注:
我知道,选择排序不是很有效。这仅用于学习目的。我不是在寻找已经是C#一部分的替代算法或类。) System.String类有一个静态方法,如果第一个字符串小于第二个字符串,则返回负数;如果它们相等,则返回零;如果第一个字符串较大,则返回正整数 我所说的“小”是指它在词汇顺序上排在另一个之前,而“大”是指它在词汇顺序上排在另一个之后
因此,您可以比较
String.compare(arr[j],arr[pos\u min])<0
而不仅仅是整数的arr[j]
。IComparable
是一个接口,它为我们提供了一个调用的函数,这是一个比较运算符。此运算符适用于实现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;
A 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;
}
}
}
//对于所有类型A,其中A是IComparable的子类型
公共无效选择排序(A[]arr)
其中A:I可比较
{
//pos_min是min位置的缩写
int pos_min;
临时工;
对于(int i=0;i Josh但是你也可以对字符串使用诸如
、=
和!=
之类的运算符。不需要循环遍历字符。不确定你在寻找什么-如果你不能使用内置的字符串比较,你必须编写某种for循环来比较字符。太棒了!非常感谢。:)我有点不确定不过使用了。层次结构仅仅是由unicode表中字符的索引决定的吗?我想知道这些字符串的排序顺序是什么:“aa”-“äb”-“ac”和“ea”-“éb”-“ec”。您可以尝试一下,看看。另外,您还可以参考文档了解更多信息。
import sys
A = ['Chuck', 'Ana', 'Charlie', 'Josh']
for i in range(0, len(A)):
min_val = i
for j in range(i+1, len(A)):
if A[min_val] > A[j]:
min_val = j
(A[min_val], A[i]) = (A[i], A[min_val])
print("Sorted Array is :")
for i in range(len(A)):
print("%s" % A[i])