In: Computer Science
**C++ program**
Please provide a header file(bubble_sort.h) and a program file(bubble_sort.cpp). Also include notes to explain code and output screenshots. Please use Bubble Sort code provided.
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
BubbleSort ----
void bubbleSort(int arr[], int n) {
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++) {
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
//bubble_sort.cpp
#include <fstream>
#include "bubble_sort.h"
using namespace std;
#define SIZE 100; //array size
//Function Declaration
int readData(int *arr);
void writeToConsole(int * arr, int last);
int main(int argc, char const *argv[])
{
int arr[SIZE];
int *ptr=&arr;
int numOfElements=readData(ptr); //calling of
Read Data Function
writeToConsole(ptr,numOfElements);
return 0;
}
int readData(int *arr){
ifstream inFile;
inFile.open("data.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
int num;
int count;
inFile >> count;
while (inFile >> num) {
*arr=num;
arr++;
}
return count;
}
void writeToConsole(int * arr, int last){
//Function to print the sorted order in the
console
bubble_sort(arr,last); //bubble_sort function
from bubble_sort.h
cout<<"The Sorted List is\n";
for(int i=0;i<last;i++){
cout<<(*arr);
arr++;
}
}
//bubble_sort.h
void bubbleSort(int arr[], int n) {
//Acc. to the Question
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++) {
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}