Question: // Hi I'm trying to trim this array to exclude duplicates and I'm completely lost. Any help would be greatly appreciated. /* Project4.java InsertInOrder with

// Hi I'm trying to trim this array to exclude duplicates and I'm completely lost. Any help would be greatly appreciated.

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

for ( int i=0; i

trimmedArr[i] = oldArr[i];

if (trimmedArr[i]!=trimmedArr[i+1])

return trimmedArr;

}

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

{

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

//not sure how to exclude repeating values

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

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!