Write a c program to use insertion sort The program should d
Write a c++ program to use insertion sort. The program should do the following:
1. Read the integer values from the file A1.txt and store them into an integer array.
2. sort the values using the insertion sort algorithm
3. save the sorted values in a file named A2Output.txt
The c++ implimentation of insertion sort is:
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
The contents of A1.txt are:
Solution
// including libraries
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
// Declararing array with default 100 values
int num[100];
// funciton prototype for insertion sort as given
void insertionSort(int arr[],int length);
// Execution point
int main()
{
// count to coutn the number of variables
int count=0;
// integer to read the number from file
int no;
// file name A1.txt
char fName[]=\"G://files/A1.txt\";
// ifstream to read the numbers
ifstream numbersFile;
// opening the file taht consists the numbers
numbersFile.open(fName);
// checking the file
if(!numbersFile.is_open())
{
count<<\"Fail to open\";
return 0;
}
// while condition to read the numbers from the file
while(numbersFile >> no)
{
// loading the number to array
num[count]= no;
// incrementing the counter
count++;
}
// calling given insertion sort method to sort the numbers
insertionSort(num,count);
int i;
// A string to store all numbers as a string
std::string res=\"\";
// loop to collect all numebrs from array
// Remeber you can also store each and every number individually
for(i=0;i<count;i++)
{
// appending to the existing string
res=res+ num[i];
}
// Logic to wrtite the string to the file
std::ofstream out(\"G://files/A2.txt\");
out << res;
out.close();
return 0;
}
// Function as given above
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}


