I have a program to load and sort an array of 20 elements. The user enters however many doubles they want and then the array is sorted and displayed. I can't figure out how to get the sort to happen the fewest number of times - meaning if after 2 passes, the array is sorted, I want it to stop. What I have seems to make sense to me, but what happens right now is that the largest number gets dropped and 0.0 is placed in the array[0] element.
Here it is..., Thanks in advance for suggestions.
#include <iostream>
#include <iomanip>
using namespace std;
int loadarray (double []);
void display (double [], int);
void sortarray(double [], int);
void main ()
{
double array1 [20] = {0.0};
int numgood;
char junk;
numgood = loadarray(array1);
sortarray(array1, numgood);
display(array1, numgood);
}
int loadarray (double array1[])
{ int num = 0;
char response = 'Y';
while (toupper(response) == 'Y')
{ cout << "\nEnter double #" << num + 1 << ": ";
cin >> array1[num];
num++;
cout << "Enter another? Y/N: ";
cin >> response;
}
return num;
}
void display (double array1[], int num)
{
cout << setw(10) << "Element" << setw(10) << "Value\n";
cout << setiosflags ( ios::fixed | ios::showpoint ) << setprecision(2);
for (int x = 0; x < num; x++)
{ cout << setw(10) << x + 1 << setw(10) << array1[x] << endl;
}
}
void sortarray (double array1[], int num)
{
double temp;
int change = 1;
for (int pass = 0; pass < num - 1; pass++)
{ for (int i = 0; i < num - pass; i++)
{ if ( array1[i] > array1[i + 1])
{ temp = array1[i];
array1[i] = array1[i+1];
array1[i+1] = temp;
change = 1;
}
else
{ change = 0;
}
}
if (change == 0)
break;
}
}