I need to create a bubble sort program that will read a text file with 100 integers in it, bubble sort it, and output a text file with it sorted as a 10x10 tabular form and on the bottom it has to specify how many passes it took to sort out the numbers.
Right now I am simply just trying to work on the basic level of just getting the program to grab the text file, read the integers, sort them, and then print them out in a new file.
However, when the program runs it doesn't print it out in a 10x10 form. On top of that I can't get it to go through my bubble sort function or get it to write to a file at the moment so I'm just trying to figure out how to read the text file, send it to a 2 dimensional array, and print it out.
I can't find out what to do and I've searched extensively about sorting and grabbing files.
You need to output a newline character for every 10 values you print out.
1 2 3 4 5 6 7
for (int i=0; i<10; i++){
for (int j=0; j<10; j++){
data >> arr[i][j];
cout << arr[i][j] << ", ";
}
cout << endl;
}
You don't need to put the numbers in a grid to print them out in a grid. You can use a 1-d array (which suits your bubblesort function) and calculate the appropriate one-dimensional index to print out with i and j like so: cout << arr[i * 10 + j].
Thanks for your response. I tried putting what you suggested in there but it didn't work, but I did change it back to a single array with a new line added on to the output. I also switched back to a single dimensional array and I passed it through the bubble sort, but I got a lot of garbage values, my text file has this: 100 94 59 83 7 11 92 76 37 89 74 59 65 79 49 89 89 75 64 82 15 74 82 68 92 61 33 95 91 82 89 64 43 93 86 65 72 40 42 90 81 62 90 89 35 81 48 33 94 81 76 86 67 70 100 80 83 78 96 58
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
usingnamespace std;
void bubbsort(int arr[]);
int main(){
char file[100];
constint a=100;
int count=0;
string line;
constint b=10;
int z=100;
int arr[a];
cout << "Please enter the name of the file: " << endl;
cin >> file;
ifstream data(file);
if (data.is_open()){
char j='\n';
for (int i=0; i<100; i++){
data >> arr[i];
bubbsort (arr);
cout << arr[i] <<'\n';
}
}
data.close();
system("pause");
return 0;
}
void bubbsort (int arr[]){
for (int i=0; i<=99; i++){
for (int j=i+1; j<=100; j++){
int temp;
if(arr[i]>arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
Also at the end when the program finishes it tells me that there is an error that the stack around variable 'arr' was corrupted. I'm loosing hair because of this :(
With a help of a buddy of mine we were able to figure out how to get it done. In case anyone needs a reference of something similar to this I'll post our results: