[英]Switch an array sort from descending order to ascending order
因此,我的程序具有將文本文件中的數字讀入數組,然后按升序對它們進行排序的功能。 但是,我的代碼不是按升序排序,而是按降序排序。 為了使我的代碼按我需要的方式工作,我需要在此處進行哪些更改?
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;
}
您應該更改此行:
if (numbers[j] < numbers[j + 1])
請改用以下代碼:
if (numbers[j] > numbers[j + 1])
基本思想確實很簡單,在第二種情況下,您要檢查一個數字是否大於其后繼數字,而在第一種情況下,您要檢查相反的數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.