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

时间:2015-12-08 22:11:32

标签: c++ arrays sorting

所以我的程序有一个函数,我将文本文件中的数字读入数组,然后按升序对它们进行排序。但是,我的代码不是按升序排序,而是按降序排序。为了让我的代码按照我需要的方式工作,我需要在这里进行哪些更改?

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;
}

1 个答案:

答案 0 :(得分:1)

您应该更改此行:

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

请改用以下内容:

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

基本的想法确实非常简单,在第二种情况下,你正在检查一个数字是否大于其继承者,而在第一个检查相反的情况下。