From 50bb225eb1232b046b97bbc0d42bc6054786d2ff Mon Sep 17 00:00:00 2001 From: Uday Vig Date: Tue, 2 Oct 2018 16:22:30 +0530 Subject: [PATCH] InsertionSort.java implements Insertion Sort in Java Added insertion sort implemenation in java. Closes issue #153. --- insertion_sort/Java/InsertionSort.java | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 insertion_sort/Java/InsertionSort.java diff --git a/insertion_sort/Java/InsertionSort.java b/insertion_sort/Java/InsertionSort.java new file mode 100644 index 00000000..e3475dac --- /dev/null +++ b/insertion_sort/Java/InsertionSort.java @@ -0,0 +1,33 @@ +import java.util.Scanner; + +public class InsertionSort { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner s = new Scanner(System.in); + System.out.println("Enter size: "); + int n = s.nextInt(); + int[] arr = new int[n]; + System.out.println("Enter elements: "); + for (int i = 0; i < n; i++) { + arr[i] = s.nextInt(); + } + insertionsort(arr); + + } + + public static void insertionsort(int arr[]) { + for (int i = 0; i < arr.length; i++) { + for (int j = i; j > 0; j--) { + if (arr[j] < arr[j - 1]) { + int temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + } + } + } + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } + } +}