Question Write a c program to use insertion sort The pro Sav
Question: Write a c++ program to use insertion sort. The pro...
Save
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 in decreasing order using bubble sort algorithm
3. save the sorted values in a file named A3Output.txt
The c++ implimentation of bubble sort is:
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;
}
}
}
}
The contents of A1.txt are:
Solution
//Program for Insertion Sort
#include <iostream>
using namespace std;
int main()
 {
 int array[2000],temp,n;
   
 cout<<\"Enter the number of elements\"<<endl;
 cin>>n;
   
 cout<<\"Enter the elements\"<<endl;
 for (int i = 0; i < n; i++)
 {
 cin>>array[i];
 }
   
 for (int i = 1; i < n; i++)
 {
 for (int j = i; j >= 1; j--)
 {
 if (array[j] < array[j-1])
 {
 temp = array[j];
 array[j] = array[j-1];
 array[j-1] = temp;
 }
 else
 break;
 }
 }
 cout<<\"Sorted array\ \"<<endl;
 for (int k = 0; k < n; k++)
 {
    cout<<array[k]<<endl;
 }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Program for bubble sort
#include <iostream>
 #include <fstream>
 using namespace std;
int bubbleSort(int arr[],int n)
 {
    bool swapped=true;
 int j=0, 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;
 }
 }
 }
 }
 int main()
 {
    int arr[2000];
    string inputFile=\"A1.txt\";
    ifstream infile(inputFile.c_str());
    if(!infile)
    {
        cout<<\"input file not found\";
        exit(0);
    }
    int n=0;
    while(!infile.eof())
    {
        infile>>arr[n++];
    }
   
    string outputFile=\"A3Output.txt\";
    bubbleSort(arr,n) ;
    ofstream outfile(outputFile.c_str());
    if(!outfile)
    {
        cout<<\"output file not found\";
        exit(0);
    }
   
    for(int i=0;i<n;i++)
    {
        outfile<<endl<<arr[i];
    }
    cout<<endl<<\"Output stored in \"<<outputFile;
    return 0;
 }



