Update SelectionSort2.java (#184)

* Update SelectionSort2.java

Small method

* Update SelectionSort2.java
This commit is contained in:
Sergey Ivanov
2022-11-18 23:58:46 +03:00
committed by GitHub
parent cf78943cef
commit 3868623fcd

View File

@@ -3,45 +3,23 @@ import java.util.Arrays;
public class SelectionSort2 { public class SelectionSort2 {
// this version uses raw arrays instead of ArrayList // this version uses raw arrays instead of ArrayList
private static int[] selectionSort(int[] arr) { public static void selectionSort(int[] target) {
int[] newArr = new int[arr.length]; for (int i = 0; i < target.length - 1; i++) {
int left = target[i];
for (int i = 0; i < newArr.length; i++) { for (int j = i + 1; j < target.length; j++) {
int smallestIndex = findSmallest(arr); int right = target[j];
newArr[i] = arr[smallestIndex]; if (left > right) {
target[i] = right;
arr = getNewArrWithoutSmallest(arr, smallestIndex); target[j] = left;
} left = right;
}
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];
} }
} }
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) { public static void main(String[] args) {
int[] arr = {5, 3, 6, 2, 10}; 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]
} }
} }