Skip to content

Commit e4b95bd

Browse files
PolurivalegonSchiele
authored andcommitted
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
1 parent 7491aa5 commit e4b95bd

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

02_selection_sort/java/src/SelectionSort2.java

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,34 @@ public class SelectionSort2 {
44

55
// this version uses raw arrays instead of ArrayList
66
private static int[] selectionSort(int[] arr) {
7-
int[] newArr = new int[]{arr.length};
7+
int[] newArr = new int[arr.length];
88

99
for (int i = 0; i < newArr.length; i++) {
10-
int smallest = findSmallest(arr, i);
11-
newArr[i] = arr[smallest];
10+
int smallestIndex = findSmallest(arr);
11+
newArr[i] = arr[smallestIndex];
12+
13+
arr = getNewArrWithoutSmallest(arr, smallestIndex);
1214
}
1315

1416
return newArr;
1517
}
1618

17-
private static int findSmallest(int[] arr, int low) {
18-
int smallest = arr[low];
19-
int smallestIndex = low;
20-
for (int i = low + 1; i < arr.length; i++) {
19+
private static int[] getNewArrWithoutSmallest(int[] arr, int smallestIndex) {
20+
int[] newArrWithoutSmallest = new int[arr.length - 1];
21+
for (int i = 0; i < arr.length; i++) {
22+
if (i < smallestIndex) {
23+
newArrWithoutSmallest[i] = arr[i];
24+
} else if (i > smallestIndex) {
25+
newArrWithoutSmallest[i - 1] = arr[i];
26+
}
27+
}
28+
return newArrWithoutSmallest;
29+
}
30+
31+
private static int findSmallest(int[] arr) {
32+
int smallest = arr[0];
33+
int smallestIndex = 0;
34+
for (int i = 0; i < arr.length; i++) {
2135
if (arr[i] < smallest) {
2236
smallest = arr[i];
2337
smallestIndex = i;
@@ -30,4 +44,4 @@ public static void main(String[] args) {
3044
int[] arr = {5, 3, 6, 2, 10};
3145
System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10]
3246
}
33-
}
47+
}

0 commit comments

Comments
 (0)