From fbf95c61f054695bfeb070ac60684a55a277407e Mon Sep 17 00:00:00 2001 From: Beppe Date: Fri, 17 Jan 2020 22:59:44 +0100 Subject: [PATCH] last index gets remembered now during insertion sort --- src/com/beppe/sorts/insertionSort.java | 32 ++++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/com/beppe/sorts/insertionSort.java b/src/com/beppe/sorts/insertionSort.java index 589fef1..5ab323e 100644 --- a/src/com/beppe/sorts/insertionSort.java +++ b/src/com/beppe/sorts/insertionSort.java @@ -2,21 +2,33 @@ package com.beppe.sorts; public class insertionSort { - public static void Sort(int[] arrayToSort, int accumulator) { + public static void Sort(int[] arrayToSort, int accumulator, int lastIndex) { if (accumulator == arrayToSort.length-1) return; - if (arrayToSort[accumulator] <= arrayToSort[accumulator+1]) Sort(arrayToSort, accumulator+1); - else { - int curr = arrayToSort[accumulator]; - int next = arrayToSort[accumulator+1]; - arrayToSort[accumulator+1] = curr; - arrayToSort[accumulator] = next; - if (accumulator != 0) Sort(arrayToSort, accumulator-1); - else Sort(arrayToSort, accumulator); + if (lastIndex != -1) { + if (arrayToSort[accumulator] > arrayToSort[accumulator+1]) { + int curr = arrayToSort[accumulator]; + int next = arrayToSort[accumulator+1]; + arrayToSort[accumulator+1] = curr; + arrayToSort[accumulator] = next; + if (accumulator != 0) Sort(arrayToSort, accumulator-1, lastIndex); + else Sort(arrayToSort, lastIndex, -1); + } + } else { + if (arrayToSort[accumulator] <= arrayToSort[accumulator+1]) Sort(arrayToSort, accumulator+1, -1); + else { + int curr = arrayToSort[accumulator]; + int next = arrayToSort[accumulator+1]; + arrayToSort[accumulator+1] = curr; + arrayToSort[accumulator] = next; + if (accumulator != 0) Sort(arrayToSort, accumulator-1, accumulator); + else Sort(arrayToSort, accumulator, -1); + } } + } public static void Sort(int[] arrayToSort) { - Sort(arrayToSort, 0); + Sort(arrayToSort, 0, -1); } }