Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

//How would I exclude the ending 0's from my trimmedArray without importing anything else? /* Project4.java InsertInOrder with bSearch optimization to compute insertion index */

//How would I exclude the ending 0's from my trimmedArray without importing anything else?

/* Project4.java InsertInOrder with bSearch optimization to compute insertion index */

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 ];

int indexJ=0;

for(int indexI=0;indexI

{

Integer currentElement =oldArr[indexI];

if(currentElement!=oldArr[indexI+1])

trimmedArr[indexJ++]=currentElement;

}

trimmedArr[indexJ++]=oldArr[count-1];

return trimmedArr;

}

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

{

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

if ( idx < 0 )

idx=-(idx+1);

int pos = count;

while(pos>0 && newVal<(arr[pos-1]))

{

arr[pos]=arr[pos-1];

pos--;

}

arr[idx] = newVal;

return true;

}

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

{

int lo =0;

int hi=count-1;

int mid = 0;

while(lo<=hi)

{

mid=lo +(hi-lo)/2;

if(a[mid]>key)

hi=mid-1;

else if(a[mid]

lo=mid+1;

else

return -(mid+1);

}

return -(lo+1);

}

}// END PROJECT4

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

Database Internals A Deep Dive Into How Distributed Data Systems Work

Authors: Alex Petrov

1st Edition

1492040347, 978-1492040347

More Books

Students also viewed these Databases questions