In: Computer Science
C++ Language
Write a program that reads the numbers.txt file and stores it into an array of integers. Use the sample functions in the text and in the notes from chapter 8 to sort the array in ascending order (low to high). You can use either method (bubble or selection sort) to accomplish this. Then store the sorted array into an output file sorted Numbers.txt. There are 100 values both positive and negative integers in this file.
//C++ code
#include<iostream>
#include<fstream>
using namespace std;
//sort array using bubble sort
void sort(int arr[], int size);
//main function
int main()
{
//Max size of an array
const int MAX = 100;
//Create array of MAX sie
int arr[MAX];
//Counter to keep track how many numbers
//has been read form file
int counter = 0;
//opern file to read
ifstream infile("numbers.txt");
//If file not found
if (!infile)
{
cout << "File not
found...\n";
return -1;
}
int num;
while (infile >> num)
{
arr[counter] = num;
counter++;
}
//Close the file
infile.close();
//sort the array
sort(arr, counter);
//open wile to write sorted array
ofstream outfile("Number.txt");
//If output file not found
if (!outfile)
{
cout << "File not
found...\n";
return -1;
}
for (int i = 0; i < counter; i++)
{
outfile << arr[i] <<
endl;
}
//close output file
outfile.close();
//pause
system("pause");
return 0;
}
void sort(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j <
size;j++)
{
if (arr[i] >
arr[j])
{
//swapping
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
//Output
//input file numbers.txt
//Output file Number.txt
//If you need any help regarding this solution........ please leave a comment........ thanks..