In: Computer Science
C++
Write a program for sorting a list of integers in ascending order using the bubble sort algorithm
Requirements
Implement the following functions:
Here is the content of the file data.txt.
9
8
4
7
2
9
5
6
1
3
If you have any doubts, please give me comment...
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int readData(int *(&arr)){
int n;
ifstream in;
in.open("data.txt");
if(in.fail()){
cout<<"unable to open file"<<endl;
return 0;
}
in>>n;
arr = new int[n];
for(int i=0; i<n; i++){
in>>*(arr+i);
}
in.close();
return n;
}
void bsort(int *arr, int last){
for(int i=0; i<last; i++){
for(int j=0; j<last-i-1; j++){
if(*(arr+j)>*(arr+j+1)){
int temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
}
}
void writeToConsole(int *arr, int last){
for(int i=0; i<last; i++){
cout<<*(arr+i)<<" ";
}
cout<<endl;
}
int main(){
int *arr;
int n;
n = readData(arr);
cout<<"Before sorting: "<<endl;
writeToConsole(arr, n);
bsort(arr, n);
cout<<"After sorting: "<<endl;
writeToConsole(arr, n);
delete[] arr;
return 0;
}