In: Computer Science
***C++ Coding***
Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. Please include comments to understand code.
Requirements
Implement the following functions:
Here is the content of the file data.txt.
9
8
4
7
2
9
5
6
1
3
// do comment if any problem arises
//code
#include <iostream>
#include <fstream>
using namespace std;
//this function reads data from data.txt
int readData(int **arr)
{
//open file for input
ifstream infile("data.txt");
//if can't open file
if (!infile.is_open())
{
cout << "Can't open input file\n";
exit(1);
}
//number of integers in data.txt
int count = 0, temp;
//read integer 1 by 1
while (infile >> temp)
{
*(*(arr) + count) = temp;
count++;
}
//close file
infile.close();
return count;
}
//this function sorts given array of size last using bubble sort
void bsort(int *arr, int last)
{
//for i from 0 to last -1
for (int i = 0; i < last - 1; i++)
{
//for j from 0 to last-i-1
for (int j = 0; j < last - i - 1; j++)
{
// if current element is greater than next element
if (*(arr + j) > *(arr + j + 1))
{
//this performs swap of jth with j+1th element
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
//this function writes sorted array to output
void writeToConsole(int *arr, int last)
{
cout << "Sorted Data: ";
for (int i = 0; i < last; i++)
cout << *(arr + i) << " ";
cout << endl;
}
int main()
{
//create array
int *array = new int[100];
int last = readData(&array);
bsort(array, last);
writeToConsole(array, last);
delete[] array;
}
data.txt:
Output: