Hello There,
Some instruction to remember before running program :
1. File that has values must contain inside the folder where a program is located.
2. Must have to provide .txt extension with a file name in a program such as if your file name is sample then string should be sample.txt
3. You have to save all the program separately
4. All the exceptions and other requirement has been handled
5. Just copy the program and save as .java and create .class file for both program
6. A file which has values have to created by you
7. Please change your name is a program where I specified
8. An output is attached to the program
9. The program has two class so save as same name as the class
Class InsertionSortClass :
public class InsertionSortClass{
static void sort(double array[],int len)
{
int i, j;
double key ;
for (i = 1; i < len; i++)
{
key = array[i];
j = i-1;
while (j >= 0 && array[j] < key)
{
array[j+1] = array[j];
j = j-1;
}
array[j+1] = key;
}
}
}
class UserInterfaceClass :
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class UserInterfaceClass extends InsertionSortClass
{
public static void main(String args[])
{
InsertionSortClass obj = new InsertionSortClass();
ArrayList<String> rows = null ;
File input = null ;
String inputFileName;
System.out.println(“Hello there ! My name is “) ; //Yourname here
// double[] arr1 = {9,14,3,2,43,11,58,22}; //you can statically provide value here and pass as parameter in fuction too
try
{
System.out.print(“Enter File Name — > “); //note filename must contains .txt extension in input
Scanner sc = new Scanner(System.in ); //Enter File name
inputFileName = sc.nextLine().trim();
input = new File(inputFileName);
System.out.println(“File Name : ” +inputFileName + “n”);
try{
rows = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(input));
String s;
while((s = reader.readLine())!=null)
rows.add(s);
reader.close();
}
catch(FileNotFoundException file)
{
System.out.println(“No such File available”);
}
catch(NumberFormatException num)
{
System.out.println(“File Doesnt Contains number values”);
}
catch(IOException e)
{
System.out.println(e);
}
double[] arr1 = new double[rows.size()]; //convert value of file that is string into double
for (int i = 0; i < rows.size(); ++i) { //iterate over the elements of the list
arr1[i] = Double.parseDouble(rows.get(i)); //store each element as a double in the array
}
System.out.println(“****** Before Insertion Sort ******”);
for(double i:arr1){
System.out.print(i+” n”);
}
System.out.println();
int number = arr1.length ; //no limit in number of values
InsertionSortClass.sort(arr1 ,number) ;
System.out.println(“****** After Insertion Sort *******”);
for(double i:arr1){ //print array
System.out.print(i+” n”);
}
}
catch(NullPointerException empty)
{
System.out.println(“Sorry File is empty”);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
output : 