From dda3325bbdad0a0b6ca928bbc664d3cfd3bc47a9 Mon Sep 17 00:00:00 2001 From: heygroot <65673927+heygroot@users.noreply.github.com> Date: Thu, 1 Oct 2020 12:09:46 +0530 Subject: [PATCH] Create insertionsort.java --- insertionsort.java | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 insertionsort.java diff --git a/insertionsort.java b/insertionsort.java new file mode 100644 index 0000000..124846f --- /dev/null +++ b/insertionsort.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.Scanner; +import java.io.IOException; +import java.io.File; + +public class InsertionSort{ + + void sorting(ArrayList arr) + { + int n = arr.size(); + for (int i = 1; i < n; i++) { + //int element = arr.get(i); + for (int j = i; j > 0; j--){ + int e1 = arr.get(j); + int e2 = arr.get(j-1); + if (e2 > e1){ + arr.set(j, e2); + arr.set(j-1,e1); + } + } + } + } + + public static void main(String args[]) throws IOException + { + InsertionSort obj = new InsertionSort(); + String pathToFile = "./Sorting/unsorted.txt"; + File unsorted = new File(pathToFile); + Scanner sc = new Scanner(unsorted); + sc.useDelimiter(","); + ArrayList arr = new ArrayList(); + while(sc.hasNext()){ + arr.add(sc.nextInt()); + } + obj.sorting(arr); + System.out.println("Sorted array"); + + System.out.println( arr); + sc.close(); + } + + +}