From 94808c7cc67d8732bac7d135f2119470435f55ed Mon Sep 17 00:00:00 2001 From: MrGeorgen Date: Sat, 26 Dec 2020 20:03:06 +0100 Subject: [PATCH] reverse descending --- .../git/MrGeorgen/timsort/timsort.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/redstoneunion/git/MrGeorgen/timsort/timsort.java b/src/main/java/de/redstoneunion/git/MrGeorgen/timsort/timsort.java index ca2f6af..63464fc 100644 --- a/src/main/java/de/redstoneunion/git/MrGeorgen/timsort/timsort.java +++ b/src/main/java/de/redstoneunion/git/MrGeorgen/timsort/timsort.java @@ -39,15 +39,30 @@ public class timsort { int j = i; boolean ascending = true; boolean descending = true; + boolean ascendingCache = false; + boolean descendingCache = false; for(; i < unsorted.length - 1 && (ascending || descending); ++i) { + ascendingCache = ascending; + descendingCache = descending; ascending = ascending && unsorted[i] <= unsorted[i + 1]; descending = descending && unsorted[i] >= unsorted[i + 1]; } if(i - j < minRun) i = j + minRun; - if(i >= unsorted.length - 1) i = unsorted.length; - runs.add(Arrays.copyOfRange(unsorted, j, i)); + boolean minRunNotMet = i >= unsorted.length - 1; + if(minRunNotMet) i = unsorted.length; + int[] temp1 = Arrays.copyOfRange(unsorted, j, i); + if(!ascendingCache && descendingCache && !minRunNotMet) { + // reverses the array + int l, temp; + for(l = 0; l < temp1.length / 2; l++) { + temp = temp1[l]; + temp1[l] = temp1[temp1.length - l - 1]; + temp1[temp1.length - l - 1] = temp; + } + } + runs.add(temp1); } - int[][] notMerged= new int[runs.size()][]; + int[][] notMerged = new int[runs.size()][]; for(int i = 0; i < runs.size(); ++i) { notMerged[i] = insertionsort(runs.get(i)); }