图书类
class Book : IComparable<Book>
{
public string ISBN;
public string Title;
public string Author;
public Book(string ISBN, string Title, String Author)
{
this.ISBN = ISBN;
this.Title = Title;
this.Author = Author;
}
public override string ToString()
{
return Title + " by " + Author + " ISBN: " + ISBN;
}
}我的快速排序
它将不接受我的book类作为有效的数据类型。
private static void QuickSort<T>(T[] items, int left, int right) where T: IComparable
{
int i, j;
i = left; j = right;
T pivot = items[left];
while (i <= j)
{
for (; (items[i].CompareTo(pivot)<0) && (i.CompareTo(right)<0); i++) ;
for (; (pivot.CompareTo(items[j]) < 0) && (j.CompareTo(left) > 0); j--) ;
if (i <= j)
swap(ref items[i++], ref items[j--]);
}
if (left < j) QuickSort<T>(items, left, j);
if (i < right) QuickSort<T>(items, i, right);
}主
用于调用分类器
static void Main(string[] args)
{
string[] array1 = { "Fred", "Zoe", "Angela", "Umbrella", "Ben" };
string[] titles = {"Writing Solid Code",
"Objects First","Programming Gems",
"Head First Java","The C Programming Language",
"Mythical Man Month","The Art of Programming",
"Coding Complete","Design Patterns",
"ZZ"};
string[] authors ={ "Maguire", "Kolling", "Bentley", "Sierra", "Richie", "Brooks", "Knuth", "McConnal", "Gamma", "Weiss" };
string[] isbns = { "948343", "849328493", "38948932", "394834342", "983492389", "84928334", "4839455", "21331322", "348923948", "43893284", "9483294", "9823943" };
Book[] library = new Book[10];
//add books in the array
for (int i = 0; i < library.Length; i++)
{
library[i] = new Book(isbns[i], titles[i], authors[i]);
}当尝试对类书的库进行排序时,代码将不接受图书作为IComparable。
QuickSort(library, 0, library.Length - 1);
Console.Write(Environment.NewLine);发布于 2020-03-23 22:48:15
您的QuickSort类指定T必须实现IComparable。
IComparable (非泛型)与IComparable<T>(泛型)不同,因此如果您更改为此,它将起作用:
private static void QuickSort<T>(T[] items, int left, int right)
where T: IComparable<T>https://stackoverflow.com/questions/60822431
复制相似问题