Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Essential Data Protection For Estate Agencies In Singapore 2024

Authors: Yang Yen Thaw Yt

1st Edition

B0CQK79WD3, 979-8872095392

More Books

Students also viewed these Databases questions