From 8090abf7f55dab1abbf63310a6dbed344c8edabf Mon Sep 17 00:00:00 2001 From: id4 Date: Sat, 26 Oct 2024 23:34:16 +0300 Subject: [PATCH] fix crititcal error plus add new universal method InsertionSort.java --- InsertionSort.java | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/InsertionSort.java b/InsertionSort.java index 10219f093..762007523 100644 --- a/InsertionSort.java +++ b/InsertionSort.java @@ -1,14 +1,34 @@ -// сортировка вставками + public class InsertionSort { - public static insertionSort(int[] arr) { + /** + * сортировка вставками по убыванию + */ + public static void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int x = arr[i]; int j = i - 1; - while (j > 0 && arr[j] < x) { + while (j >= 0 && arr[j] < x) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = x; } } + + /** + * Сортировка вставками по возрастанию + * @param list принимает список, элементы которого реализуют интерфейс {@code Comparable} + * @throws UnsupportedOperationException если список неизменяемый (unmodifiable) + */ + public static > void insertionSort(List list) { + for (int i = 1; i < list.size(); i++) { + T value = list.get(i); + int j = i - 1; + while (j >= 0 && list.get(j).compareTo(value) > 0) { + list.set(j + 1, list.get(j)); + j--; + } + list.set(j + 1, value); + } + } }