***C++ CODING***
Write a program for sorting a list of integers in ascending order using the bubble sort algorithm.
Requirements
Implement the following functions:
The function returns a pointer that points to the locations with integers reading from the file data.txt.
arr is a pointer for storing the integers. The function returns
the number of integers.
The function readData reads the list of integers from a file call
data.txt into the array arr. The first integer number in the file
is the number of intergers. After the first number, the file lists
the integers line by line.
2. void bsort(int *arr, int last)
arr is a pointer to an array of integers to be sorted. last is the
number of elements in the array. The function bsort sorts the list
of integers in ascending order.
Here is the Link to the Bubble Sort.
3. writeToConsole(int * arr, int last)
arr is a pointer to an array of integers. last is
the number of elements in the array. The function writeToConsole
displays the sorted list.
4. Do not use the array notation in your solution.
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 &n){
ifstream in;
in.open("data.txt");
if(in.fail()){
cout<<"unable to open file"<<endl;
return 0;
}
in>>n;
int *arr = new int[n];
for(int i=0; i<n; i++){
in>>*(arr+i);
}
in.close();
return arr;
}
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;
arr = readData(n);
cout<<"Before sorting: "<<endl;
writeToConsole(arr, n);
bsort(arr, n);
cout<<"After sorting: "<<endl;
writeToConsole(arr, n);
delete[] arr;
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.