Wednesday, May 2, 2018

Insertion Sort to sort names.

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

/* File      :InsertionSort.java 
* Author     :blnakbug
* Date       :05/01/2018 
* ----------------------------- 
* OVERVIEW 
* ======== 
* This is a simple program to 
* sort a list of names. This program 
* does it by implementing the 
* concept of insertion sort. 
*/
 
 
 public class InsertionSort {

    public static void main(String[] args) {
        ArrayList arr = new ArrayList<>();

        String name = args[0];
        File file = new File(name);
        try{
            Scanner input = new Scanner(file);
            while(input.hasNextLine()){
                String line = input.nextLine();
                Scanner lineScan = new Scanner(line);

                while(lineScan.hasNext()){
                    String nameSort = lineScan.next();
                    String names = nameSort.toLowerCase();
                    arr.add(names);

                }
                lineScan.close();
            }
            input.close();
        }catch(Exception e){
            System.err.print("File doesn't exist.");
        }


        sorting(arr);
        System.out.printf("\tSorting list containing %d names....\n",arr.size());


        System.out.println("\t--------------------------------\n");
        for(int i = 0 ; i < arr.size();i++){
            System.out.printf("\t%s\n",arr.get(i));
        }
    }

    //method for sorting 
   public static void sorting(ArrayList list){
        for(int i = 1;i< list.size();i++){
            String key = list.get(i);
            int j = i - 1;
            while(j >= 0 && list.get(j).compareTo(key) > 0){
                String temp = list.get(j);
                list.set(j,list.get(j+1));
                list.set(j+1, temp);
                j--;

            }

        }
    }
}
 
/* 
* Note 
* Visit github  for the test file. 
* Usages: java InsertionSort [filename]
*/
 
 
 

No comments: