In: Computer Science
The program should be able to do the following: In Java
accepts one command line parameter. The parameter specifies the path to a text file containing the integers to be sorted. The structure of the file is as follows:
There will be multiple lines in the file (number of lines unknown).
Each line will contain multiple integers, separated by a single whitespace.
reads the integers from the text file in part a into an array of integers.
sort the integers in ascending order, and then prints out a sorted version of these integers, one per line
Implements the selection sort algorithm.
Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args)
{
int []arr=new int[1000];
int count=0;
String line;
BufferedReader reader;
try
{
reader = new BufferedReader(new FileReader(args[0]));
line = reader.readLine();
while (line != null)
{
// read next line
String []value=line.split(" ");
for(int i=0;i<value.length;i++)
{
arr[count]=Integer.parseInt(value[i]);
count++;
}
line = reader.readLine();
}
reader.close();
}
catch (IOException e)
{
System.out.println(args[1]+" file not found.");
}
System.out.println("Original Array is: ");
printArray(arr,count);
selectionSort(arr, count);
System.out.println("\n\nAfter sorting array is: ");
printArray(arr,count);
}
public static void selectionSort(int[] arr,int size)
{
for (int i = 0; i < size - 1; i++)
{
int index = i;
for (int j = i + 1; j < size; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
private static void printArray(int[] arr, int count)
{
for(int i=0;i<count;i++)
System.out.println(arr[i]);
}
}
Numbers.txt file
output
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.