Question: NEED A SIMPLE C++ CODE THAT READS IN A TEXT FILE OF INTEGERS STORES THEM IN A ARRAY AND THEN USING INSERTION SORT, SORT THE

NEED A SIMPLE C++ CODE THAT READS IN A TEXT FILE OF INTEGERS STORES THEM IN A ARRAY AND THEN USING INSERTION SORT, SORT THE ARRAY!! PLEASE HELP!!

THIS IS THE CODE I ALREADY HAVE

#include "insertionSort.h"

#include

#include

using namespace std;

#include

#include

//namespace

using namespace std;

/* Function to sort an array using insertion sort*/

void insertionSort(int arr[], int n)

{

int i, key, j;

for (i = 1; i < n; i++)

{

key = arr[i];

j = i - 1;

/* Move elements of arr[0..i-1], that are

greater than key, to one position ahead

of their current position */

while (j >= 0 && arr[j] > key)

{

arr[j + 1] = arr[j];

j = j - 1;

}

arr[j + 1] = key;

}

}

// A utility function to print an array of size n

void printArray(int arr[], int n)

{

int i;

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf(" ");

}

//start of main function

int main()

{

//variables

int count = 0, d;

int arr[100];

ifstream infile;

//open file to read

infile.open("10_Random.txt");

//check for errors in reading file

if (!infile)

{

cout << "File does not exist." << endl;

}

//start reading the files

while (infile >> d)

{

arr[count] = d;

count++;

}

cout << "Unsorted file data is: " << endl;

for (int i = 0; i< count; i++)

{

cout << arr[i] << " ";

}

cout << endl;

cout << "Data in sorted order is: ";

insertionSort(arr, count);

printArray(arr, count);

infile.close();

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!