From 10a8f8c7e04992cf7d59e1698620a1d4460f8e23 Mon Sep 17 00:00:00 2001 From: Vinamra Pankaj Sareen Date: Wed, 10 Oct 2018 22:55:55 +0530 Subject: [PATCH 1/2] Update InsertionSort.java --- InsertionSort.java | 76 +++++++++++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 32 deletions(-) diff --git a/InsertionSort.java b/InsertionSort.java index e27a9b3..cdae7e0 100644 --- a/InsertionSort.java +++ b/InsertionSort.java @@ -1,33 +1,45 @@ -// Java program for implementation of Insertion Sort -class InsertionSort{ - void sort(int arr[]){ - int n = arr.length; - for (int i=1; i=0 && arr[j] > key){ - arr[j+1] = arr[j]; - j = j-1; - } - arr[j+1] = key; - } - } - - static void printArray(int arr[]){ - int n = arr.length; - for (int i=0; i=0 && arr[j] > key) + { + arr[j+1] = arr[j]; + j = j-1; + } + arr[j+1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Tue, 16 Oct 2018 22:42:05 +0530 Subject: [PATCH 2/2] Update InsertionSort.java --- InsertionSort.java | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/InsertionSort.java b/InsertionSort.java index cdae7e0..012bcf8 100644 --- a/InsertionSort.java +++ b/InsertionSort.java @@ -2,25 +2,30 @@ class InsertionSort { /*Function to sort array using insertion sort*/ - void sort(int arr[]) - { - int n = arr.length; - for (int i=1; i=0 && arr[j] > key) - { - arr[j+1] = arr[j]; - j = j-1; - } - arr[j+1] = key; - } - } + void sort ( int A[]) { + int n=A.length; + + for( int i = 0 ;i < n ; i++ ) { + /*storing current element whose left side is checked for its + correct position .*/ + + int temp = A[ i ]; + int j = i; + + /* check whether the adjacent element in left side is greater or + less than the current element. */ + + while( j > 0 && temp < A[j-1]) { + + // moving the left side element to one position forward. + A[j] = A[j-1]; + j= j - 1; + + } + // moving current element to its correct position. + A[ j ] = temp; + } +} /* A utility function to print array of size n*/ static void printArray(int arr[])