C++ Question: Insertion Sort on a File I: Write a program that uses an initially
ID: 3919285 • Letter: C
Question
C++ Question:
Insertion Sort on a File I:
Write a program that uses an initially empty file to store a sorted list of integers entered by the user. The integers are stored in binary form. Each time the program is run, it opens the file and outputs the list of stored integers onto the screen. The program then asks the user to enter a new integer X. The program then looks at the integer at the end of the file. If that integer is less than or equal to X, the program stores X at the end of the file. Otherwise, the program starts at the end of the file and work towards the beginning, moving each value in the file that is greater than X up by one until it reaches the position in the file where X should be stored. The program then writes X at that position and closes the file.
Explanation / Answer
#include <iostream>
#include<vector>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream rf("C:/Users/Vamsi/Desktop/data.txt", std::ios_base::in);
int a;
//reading file...
vector<int> v;//creating integer vector..
cout<<" File contents: ";
while (rf >> a)
{
cout<<a<<endl;
v.push_back(a);
}
//closing file
rf.close();
//reading integer...
int x;
cout<<"Enter integer in binary format :";
cin>>x;
//placing in vector...in its correct position
v.push_back(x);//placing at end..
//insertion sort...
int i=v.size()-2,k;
while(i>=0)
{
if(v.at(i)>x)
{
v.at(i+1) = v.at(i);
v.at(i)=x;
}
else
{
break;
}
i--;
}
std::ofstream of;
of.open("C:/Users/Vamsi/Desktop/data.txt",std::ofstream::out | std::ofstream::trunc);
of.flush();
i=0;
while(i<v.size())
{
of<<v.at(i)<<endl;
i++;
}
cout<<x<<" inserted to file ";
of.close();
return 0;
}
output:
File contents:
1
10
11
110
Enter integer in binary format :101
101 inserted to file
Process exited normally.
Press any key to continue . . .
file contents
1
10
11
101
110
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.