From 3868623fcde97189690867a670492654721dfdcf Mon Sep 17 00:00:00 2001 From: Sergey Ivanov Date: Fri, 18 Nov 2022 23:58:46 +0300 Subject: [PATCH] Update SelectionSort2.java (#184) * Update SelectionSort2.java Small method * Update SelectionSort2.java --- .../java/src/SelectionSort2.java | 46 +++++-------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/02_selection_sort/java/src/SelectionSort2.java b/02_selection_sort/java/src/SelectionSort2.java index 8228d89..5b6b566 100644 --- a/02_selection_sort/java/src/SelectionSort2.java +++ b/02_selection_sort/java/src/SelectionSort2.java @@ -3,45 +3,23 @@ import java.util.Arrays; public class SelectionSort2 { // this version uses raw arrays instead of ArrayList - private static int[] selectionSort(int[] arr) { - int[] newArr = new int[arr.length]; - - for (int i = 0; i < newArr.length; i++) { - int smallestIndex = findSmallest(arr); - newArr[i] = arr[smallestIndex]; - - arr = getNewArrWithoutSmallest(arr, smallestIndex); - } - - return newArr; - } - - 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]; + public static void selectionSort(int[] target) { + for (int i = 0; i < target.length - 1; i++) { + int left = target[i]; + for (int j = i + 1; j < target.length; j++) { + int right = target[j]; + if (left > right) { + target[i] = right; + target[j] = left; + left = right; + } } } - 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; - } - } - return smallestIndex; } public static void main(String[] args) { int[] arr = {5, 3, 6, 2, 10}; - System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10] + selectionSort(arr); + System.out.println(Arrays.toString(arr)); // [2, 3, 5, 6, 10] } }