From e4b95bd6c4689b86aa36220db68448e98b36d80c Mon Sep 17 00:00:00 2001 From: Yury Polshchikov Date: Sun, 14 May 2017 10:48:38 +0300 Subject: [PATCH] Update SelectionSort2.java old version of sort with array was with mistake in array size in line 7. Also findSmallest method each time accepted array with already finded smallest --- .../java/src/SelectionSort2.java | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/02_selection_sort/java/src/SelectionSort2.java b/02_selection_sort/java/src/SelectionSort2.java index b70e598..8228d89 100644 --- a/02_selection_sort/java/src/SelectionSort2.java +++ b/02_selection_sort/java/src/SelectionSort2.java @@ -4,20 +4,34 @@ public class SelectionSort2 { // this version uses raw arrays instead of ArrayList private static int[] selectionSort(int[] arr) { - int[] newArr = new int[]{arr.length}; + int[] newArr = new int[arr.length]; for (int i = 0; i < newArr.length; i++) { - int smallest = findSmallest(arr, i); - newArr[i] = arr[smallest]; + int smallestIndex = findSmallest(arr); + newArr[i] = arr[smallestIndex]; + + arr = getNewArrWithoutSmallest(arr, smallestIndex); } return newArr; } - private static int findSmallest(int[] arr, int low) { - int smallest = arr[low]; - int smallestIndex = low; - for (int i = low + 1; i < arr.length; i++) { + private static int[] getNewArrWithoutSmallest(int[] arr, int smallestIndex) { + int[] newArrWithoutSmallest = new int[arr.length - 1]; + for (int i = 0; i < arr.length; i++) { + if (i < smallestIndex) { + newArrWithoutSmallest[i] = arr[i]; + } else if (i > smallestIndex) { + newArrWithoutSmallest[i - 1] = arr[i]; + } + } + return newArrWithoutSmallest; + } + + private static int findSmallest(int[] arr) { + int smallest = arr[0]; + int smallestIndex = 0; + for (int i = 0; i < arr.length; i++) { if (arr[i] < smallest) { smallest = arr[i]; smallestIndex = i; @@ -30,4 +44,4 @@ public class SelectionSort2 { int[] arr = {5, 3, 6, 2, 10}; System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10] } -} \ No newline at end of file +}