Spa*_*532 1 c# sorting generics icomparable quicksort
我想问一下我创建的排序通用类。我使用了今年学到的许多不同概念,并将其组合到一个不错的类中,可以用来对任何东西进行排序(当然,如果它是一个类,则该类具有CompareTo方法)
public class Sort<T> where T : IComparable<T>
{
private List<T> toSort;
public Sort(List<T> sortList)
{
toSort = sortList;
quickSort();
}
public void quickSort()
{
qSort(toSort, 0, toSort.Count - 1);
}
private void qSort(List<T> toSort, int left, int right)
{
//set the indexes
int leftIndex = left;
int rightIndex = right;
//get the pivot
var pivot = toSort[left + (right - left) / 2];
while (leftIndex <= rightIndex)
{
//check left values
while (toSort[leftIndex].CompareTo(pivot)<0)
{
leftIndex++;
}
//check right values
while (toSort[rightIndex].CompareTo(pivot) >0)
{
rightIndex--;
}
//swap
if (leftIndex <= rightIndex)
{
var tmp = toSort[leftIndex];
toSort[leftIndex] = toSort[rightIndex];
toSort[rightIndex] = tmp;
//move towards pivot
leftIndex++;
rightIndex--;
}
}
//continues to sort left and right of pivot
if (left < rightIndex)
{
qSort(toSort, left, rightIndex);
}
if (leftIndex < right)
{
qSort(toSort, leftIndex, right);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只有一个问题,就是我上网时使用的quickSort,然后自己将其转换为使用泛型。我了解实际排序的工作方式。我只想知道,为什么我不必退货。我有点困惑。我看到它实际上是在切换列表的值,但是我不知道它如何访问我发送的列表。因为在我称之为的地方我可以做到这一点
List<string> toSort = new List<string> { "C", "B", "A" };
Sort<string> sort = new Sort<string>(toSort);
cbxAlphabet.DataSource = toSort;
Run Code Online (Sandbox Code Playgroud)
因此,我只使用原始列表,并且comboBox中将包含A,B和C。
如果有人可以解释这一点,我将不胜感激!
编辑:
public static class Sort<T> where T : IComparable<T>
{
public static void quickSort(List<T> sortList)
{
qSort(sortList, 0, sortList.Count - 1);
}
private static void qSort(List<T> toSort, int left, int right)
{
//set the indexes
int leftIndex = left;
int rightIndex = right;
//get the pivot
var pivot = toSort[left + (right - left) / 2];
while (leftIndex <= rightIndex)
{
//check left values
while (toSort[leftIndex].CompareTo(pivot)<0)
{
leftIndex++;
}
//check right values
while (toSort[rightIndex].CompareTo(pivot) >0)
{
rightIndex--;
}
//swap
if (leftIndex <= rightIndex)
{
var tmp = toSort[leftIndex];
toSort[leftIndex] = toSort[rightIndex];
toSort[rightIndex] = tmp;
//move towards pivot
leftIndex++;
rightIndex--;
}
}
//continues to sort left and right of pivot
if (left < rightIndex)
{
qSort(toSort, left, rightIndex);
}
if (leftIndex < right)
{
qSort(toSort, leftIndex, right);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |