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
This commit is contained in:
Yury Polshchikov
2017-05-14 10:48:38 +03:00
committed by Aditya Bhargava
parent 7491aa5890
commit e4b95bd6c4

View File

@@ -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]
}
}
}