Sorting integers from a text file in java. I must write a method for sorting and
ID: 3890459 • Letter: S
Question
Sorting integers from a text file in java. I must write a method for sorting and organizing a text file of integers , and am running into issues in writing the putInOrder method. Any help would be greatly appriciated!
import java.util.*;
import java.io.*;
public class Project5
{
static final int INITIAL_CAPACITY = 10;
public static void main( String args[] ) throws Exception
{
if (args.length < 1 )
{
System.out.println(" usage: C:\> java Project P5input.txt ");
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 = upSize( arr );
insertInOrder( arr, count, infile.nextInt() );
++count;
}
infile.close();
printArray( "SORTED ARRAY: ", arr, count );
} // END MAIN
// DO NOT CHANGE
static void printArray( String caption, int[] arr, int count )
{
System.out.print( caption );
for( int i=0 ; i<count ;++i )
System.out.print(arr[i] + " " );
System.out.println();
}
// YOU WRITE THESE METHODS ONLY
static void putInOrder( int[] arr, int count, int key )
{
}
static int[] upSize( int[] fullArr )
{
{
int[] newArr=new int[fullArr.length*2];
for(int i =0;i<fullArr.length;++i){
newArr[i]=fullArr[i];
}
return newArr;
}
}
} // END
Explanation / Answer
The parameter "key" in putInOrder is not very clear.Currently taken as option for asvcending order or desecending order.The sorting function is as follows:
static void putInOrder(int[] arr, int count, key){
int temp;
if (key == 1){ //Assuming key = 1 means Ascending order
for(int i = 0; i<count; i++){
for(int j = i; j<count; j++){
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j]
arr[j] = temp;
}
}
}
}
if (key == 0){ //Assuming key = 0 means descending order
for(int i = 0; i<count; i++){
for(int j = i; j<count; j++){
if (arr[i] < arr[j]){
temp = arr[i];
arr[i] = arr[j]
arr[j] = temp;
}
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.