last index gets remembered now during insertion sort

This commit is contained in:
2020-01-17 22:59:44 +01:00
parent 8b0269445f
commit fbf95c61f0

View File

@@ -2,21 +2,33 @@ package com.beppe.sorts;
public class insertionSort { 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 (accumulator == arrayToSort.length-1) return;
if (arrayToSort[accumulator] <= arrayToSort[accumulator+1]) Sort(arrayToSort, accumulator+1); if (lastIndex != -1) {
else { if (arrayToSort[accumulator] > arrayToSort[accumulator+1]) {
int curr = arrayToSort[accumulator]; int curr = arrayToSort[accumulator];
int next = arrayToSort[accumulator+1]; int next = arrayToSort[accumulator+1];
arrayToSort[accumulator+1] = curr; arrayToSort[accumulator+1] = curr;
arrayToSort[accumulator] = next; arrayToSort[accumulator] = next;
if (accumulator != 0) Sort(arrayToSort, accumulator-1); if (accumulator != 0) Sort(arrayToSort, accumulator-1, lastIndex);
else Sort(arrayToSort, accumulator); 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) { public static void Sort(int[] arrayToSort) {
Sort(arrayToSort, 0); Sort(arrayToSort, 0, -1);
} }
} }