In: Computer Science
Overview: You will write a program that reads up to 100 numbers
from a file. As you read the
numbers, insert them into an array in ascending order.
Specifics:
1A. Write a function called insertIntoSortedArray .
i. It should take three arguments -
a. myArray[ ] : sorted array that should be able to hold at most
100 integers.
b. numEntries : the number of elements inserted so far.
c. newValue : the incoming value to be inserted into the sorted
array (i.e.
myArray[]).
ii. The insertIntoSortedArray function should return a count of the
elements inserted so
far (i.e. the current size of the array)
This function is defined as follows:
int insertIntoSortedArray ( int myArray[], int numEntries, int
newValue);
//This program is written in C
//To convert it to C++, comment the first header line and
//uncomment next two lines as written below.
#include <stdio.h> //for C
//#include <iostream> // for C++
//using namespace std; // for C++
int insertIntoSortedArray (int myArray[], int numEntries, int
newValue)
{
//corner case: array already full
if(numEntries == 100)
{
printf("Number can't be inserted,
array full\n");
return numEntries;
}
//start from the end of the array and shift all the
elements
//larger than newValue to one position right
//when this loop stops, variable i will point to one
left of the
//position of newValue
int i=numEntries-1;
while(i>=0 && myArray[i]>newValue)
{
myArray[i+1]=myArray[i];
i--;
}
myArray[i+1]=newValue;
//new size of array
numEntries++;
return numEntries;
}
//test function to check the program
void printArray(int myArray[], int numEntries)
{
for(int i=0; i<numEntries; i++)
printf("%d ", myArray[i]);
printf("\n");
}
int main()
{
int myArray[100];
int numEntries = 0;
//open file
FILE* fp = fopen("filename.txt", "r");
int newValue;
//read numbers from file
while(!feof(fp))
{
fscanf(fp,"%d",
&newValue);
numEntries =
insertIntoSortedArray(myArray,numEntries,newValue);
printArray(myArray,numEntries);
if(numEntries==100)
break;
}
//close file
fclose(fp);
return 0;
}
Output for the following input:
5 4 6 10 7 1 6 9 6