Nov 13, 2012 at 12:24am UTC
Writing a programs that get integers from a file, reads to arrays, sorts the arrays in ascending order and outputs it. But im having trouble with the sorting function: void bubbleSort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
const int MAX_NUMBERS = 25;
// function protoypes go here
int main()
{
int x[MAX_NUMBERS];
string file1, file2;
getUserInput(file1, file2);
downloadArray(file1,x);
bubbleSort(x);
outputArray(file1, file2,x);
system("pause" );
return 0;
}
void getUserInput( string &inputfile, string &outputfile )
{
cout << "Enter input file name: " ;
cin >> inputfile;
cout << endl;
cout << "Enter output file name: " ;
cin >> outputfile;
}
void downloadArray ( string &inputfile, int array[MAX_NUMBERS])
{
ifstream input;
input.open(inputfile.c_str() );
while (input >> array[MAX_NUMBERS])
{
cout << array[MAX_NUMBERS] << " " ;
}
input.close();
}
int bubbleSort(int array[MAX_NUMBERS])
{
int i, j;
swapNumbers(array);
for (i = 0; i <= (MAX_NUMBERS - 1); i++ )
{
for (j = i+1; j <= MAX_NUMBERS; j++ )
{
int temp;
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (i = 0; i <= MAX_NUMBERS; i++ )
{
cout << array[i] << endl;
}
return i;
}
int swapNumbers(int array[MAX_NUMBERS])
{
int i;
for (i = 0; i <= MAX_NUMBERS; i++ )
{
cout << "Enter a number: " ;
cin >> array[i];
}
return i;
}
void outputArray( string &inputfile, string &outputfile, int array[MAX_NUMBERS] )
{
ifstream input;
ofstream output;
int index,y;
input.open(inputfile.c_str() );
output.open(outputfile.c_str() );
index = 0;
while (input >> array[index++])
{
}
int arrayLength = index - 1;
for (int i = 0; i < arrayLength; ++i)
{
output << bubbleSort(array[i]) << " " ;
if ( y >= 10)
{
output << "/n" << endl;
y = 0;
}
y++;
}
output.close();
}
Last edited on Nov 13, 2012 at 1:34am UTC
Nov 13, 2012 at 1:25am UTC
I did not see all your code because it will be enough to point out that this function is invalid
void downloadArray ( string &inputfile, int array[MAX_NUMBERS])
{
ifstream input;
input.open(inputfile.c_str() );
while(input >> array[MAX_NUMBERS])
{
cout << array[MAX_NUMBERS] << " ";
}
input.close();
}
You are trying to read all file data in one element of the array with index MAX_NUMBERS and I am afraid that this index is beyond the acceptable range of ndexes for the array.
Last edited on Nov 13, 2012 at 1:26am UTC