冒泡排序在 3 个输入后反转整个列表

Bubble sort reversing entire list after 3 inputs

所以我试图按字母顺序对已添加到数组中的书籍列表进行排序,但是,每当我输入第三本书时,列表就会翻转并按非字母顺序对列表进行排序。

如果有人知道这是为什么,请评论告诉我,我的代码在下面。

判断两个索引是否需要交换的排序

private void bookSort()
{
    for (int y = 0; y < 20; y++)
    {
        for (int x = 0; x < bookPTR - 1; x++)
        {
            if (string.Compare(books[x].GStitle, books[x + 1].GStitle) > 0)
            {
                bookSwapRoutine(books[x]);
            }
        }
    }
}

交换本身

private void bookSwapRoutine(Book book, int x = 0)
{
    string tempString = books[x].GStitle;
    books[x].GStitle = books[x + 1].GStitle;
    books[x + 1].GStitle = tempString;

    int tempInt = books[x].GSisbn;
    books[x].GSisbn = books[x + 1].GSisbn;
    books[x + 1].GSisbn = tempInt;

    tempString = books[x].GSauthor;
    books[x].GSauthor = books[x + 1].GSauthor;
    books[x + 1].GSauthor = tempString;

    tempString = books[x].GSpublisher;
    books[x].GSpublisher = books[x + 1].GSpublisher;
    books[x + 1].GSpublisher = tempString;

    double tempDouble = books[x].GSprice;
    books[x].GSprice = books[x + 1].GSprice;
    books[x + 1].GSprice = tempDouble;

    tempString = books[x].GSdate;
    books[x].GSdate = books[x + 1].GSdate;
    books[x + 1].GSdate = tempString;
}

因为这个地方。由于默认参数 x = 0,该函数调用总是在零索引和第一个索引处交换书籍。

bookSwapRoutine(books[x]);

你应该这样称呼它。

bookSwapRoutine(books[x], x);

这将为您交换 books[x] 和 books[x + 1]。

如果您只想按 GStitle 按字母顺序对书籍进行排序,您可以致电。

Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture));

如果对你有帮助,所有代码都在这里,带有正确的冒泡排序。

public static void Main()
{
    var books = new Book[]
    {
        new Book() {GStitle = "E"},
        new Book() {GStitle = "D"},
        new Book() {GStitle = "C"},
        new Book() {GStitle = "B"},
        new Book() {GStitle = "A"}
    };

    Console.WriteLine("Before sort.");
    foreach (var book in books)
    {
        Console.WriteLine(book.GStitle);
    }

    Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture));
    //BookSort(books);

    Console.WriteLine("After sort.");
    foreach (var book in books)
    {
        Console.WriteLine(book.GStitle);
    }
}

public class Book
{
    public string GStitle { get; set; }
}

public static void BookSort(Book[] books)
{
    for (int y = 0; y < books.Length; y++)
    {
        for (int x = 0; x < books.Length - 1 - y; x++)
        {
            if (string.Compare(books[x].GStitle, books[x + 1].GStitle, StringComparison.InvariantCulture) > 0)
            {
                var temp = books[x];
                books[x] = books[x + 1];
                books[x + 1] = temp;
            }
        }
    }
}