Reputation: 23
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;
}
Upvotes: 0
Views: 1488
Reputation: 50550
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.
Upvotes: 1