简体   繁体   English

将数组排序从降序切换到升序

[英]Switch an array sort from descending order to ascending order

So my program has a function in which I read the numbers from a text file into an array and then sort them in ascending order. 因此,我的程序具有将文本文件中的数字读入数组,然后按升序对它们进行排序的功能。 However, instead of sorting in ascending order my code sorts in descending order. 但是,我的代码不是按升序排序,而是按降序排序。 What do I need to change here in order to get my code to work the way I need it to? 为了使我的代码按我需要的方式工作,我需要在此处进行哪些更改?

void displaySortedNums(string fileName)
{
    ifstream inFile;
    inFile.open(fileName + ".txt");
    int numbers[50];
    int arraySize = 0;

    if (!inFile.is_open())
        {
            cerr << "\nUnable to open file " << endl << endl;
        }
    if (inFile.peek() == std::ifstream::traits_type::eof())
        {
            cout << "\nData file is empty" << endl << endl;
            cout << "File Successfully Read" << endl << endl;
        }
    else
        {
            inFile >> numbers[arraySize];
            while (inFile)
                {
                    arraySize++;
                    inFile >> numbers[arraySize];
                }
            numbers[arraySize] = '\0';
            double temp;
            for (int i = 0; i < arraySize + 1; i++)
            for (int j = 0; j < arraySize + (i + 1); j++)
                    if (numbers[j] < numbers[j + 1])
                    {
                        temp = numbers[j];
                        numbers[j] = numbers[j + 1];
                        numbers[j + 1] = temp;
                    }
            for (int i = 0; i < arraySize; i++)
            {
                cout << numbers[i] << endl;

            }
        }

    system("PAUSE");
    return;
}

You should change this line: 您应该更改此行:

if (numbers[j] < numbers[j + 1])

Use the following one instead: 请改用以下代码:

if (numbers[j] > numbers[j + 1])

The basic idea is quite simple indeed, in the second case you are checking if a number is greater than its successor while in the first one you were checking the opposite. 基本思想确实很简单,在第二种情况下,您要检查一个数字是否大于其后继数字,而在第一种情况下,您要检查相反的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM