Question: hello. I am having trouble with insertinorder method. is there any way to make it into one loop. import java.util.*; import java.io.*; public class Project4

hello. I am having trouble with insertinorder method. is there any way to make it into one loop.

import java.util.*;

import java.io.*;

public class Project4

{

static final int INITIAL_CAPACITY = 5;

public static void main( String args[] ) throws Exception

{

if (args.length < 1 )

{

System.out.println("ERROR: Must put input filename on cmd line ");

System.exit(0);

}

Scanner infile = new Scanner( new File( args[0] ) );

int[] arr = new int[INITIAL_CAPACITY];

int count= 0;

while ( infile.hasNextInt() )

{

if ( count==arr.length ) arr = upSizeArr(arr);

if (insertInOrder( arr, count, infile.nextInt() ) )

++count;

}

arr=trimArr(arr,count); // Now count == .length

printArray( arr ); // we trimmed it thus count == length so we don't bother to pass in count

}

// ############################################################################################################

static void printArray( int[] arr )

{

for( int i=0 ; i

System.out.print(arr[i] + " " );

System.out.println();

}

static int[] upSizeArr( int[] fullArr )

{

int[] upSizedArr = new int[ fullArr.length * 2 ];

for ( int i=0; i

upSizedArr[i] = fullArr[i];

return upSizedArr;

}

static int[] trimArr( int[] oldArr, int count )

{

int[] trimmedArr = new int[ count ];

for ( int i=0; i

trimmedArr[i] = oldArr[i];

return trimmedArr;

}

static boolean insertInOrder( int[] arr, int count, int newVal )

{

int index = bSearch( arr, count, newVal );

if ( index >= 0 ) return false;

boolean found=false;

for(int i=0;i

if(arr[i]>=newVal) {

index = i;

found=true;

break;

}

}

if(found) {

for (int i = count; i > index; i--) {

arr[i] = arr[i-1];

}

}else {

index=count;

}

arr[index] = newVal;

return true;

}

static int bSearch(int[] a, int count, int key)

{

int l = 0, r = count - 1;

while (l <= r) {

int m = l + (r - l) / 2;

if (a[m] == key) {

return m;

}

if (a[m] < key) {

l = m + 1;

}

else {

r = m - 1;

}

}

return -1;

}

}// END PROJECT4

EXPECTED OUTPUT

100 15 19 32 34 38 42 46 50 57 57 60 65 67 71 79 85 89 89 90 90 92 98 99 99

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!