I was given an assignment to:
"Write a function that implements the bubble sort for an array of integers. The prototype for the function is as follows: void sort(int data[], int count);
Write a program that prompts for a file name, opens that file and reads numbers from the file in to an array. Your program should then call your sort routine and then print the resulting array."
I completed it, and it was working just fine until I was told it also has to stop early if the numbers are already in order. You will see that attempt in the void function below. I'm not getting any errors; the program compiles, executes, and closes fine. The problem is now with the addition of the boolean variable it no longer sorts the numbers. It will print them out in the same order as the text file. I ran it through the debugger and noticed that the "ii" variable wasn't increasing by 1 every pass like it's supposed to , for(... ; ... ; ii++) , but instead stayed at 0. Any ideas?
The (random) numbers inside the "integers.txt" file: 12 42 5 67 41 9 19 93 10 124 21
void sort(int data[], int count);
int main()
{
const int MAX_SIZE = 128;
char fileName[MAX_SIZE];
int data[MAX_SIZE];
int count = 0;
cout << "Enter a file name: "; //integers.txt
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
cin.getline(fileName, sizeof(fileName));
ifstream input(fileName); //opens the file and reads the first line
if (input.is_open())
{
while (!input.eof() && count <= MAX_SIZE) //adds data to the array until the end of the file is reached
{
input >> data[count];
count += 1;
}
input.close();
}
else
{
cout << "\nThe file failed to open, try again.\n";
}
sort(data, count); //calls the bubble sort function
return 0;
}
void sort(int data[], int count)
{
int temp = 0;
int pass = 0;
bool sorted = false;
for (int pass = 0; pass <= count; pass += 1) //counts the number of passes
{
for (int ii = 0; (ii <= (count - pass - 1)) && (sorted = false) ; ii++) //sorts the integers from least to greatest
{ //also 'supposed to' stop early if already sorted
if (data[ii] > data[ii + 1])
{
sorted = false;
temp = data[ii];
data[ii] = data[ii + 1];
data[ii + 1] = temp;
}
}
}
cout << "\nSorted integers: ";
for (int jj = 1; jj <= count; jj += 1) //prints the sorted integers
{
cout << data[jj] << " ";
}
cout << "\n\n";
}