Skip to content

Commit 994f068

Browse files
Added the implementation of the Selection Sort algorithm
1 parent 6e238ad commit 994f068

2 files changed

Lines changed: 46 additions & 6 deletions

File tree

‎src/com/sketch/Main.java‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
package com.sketch;
22

3-
import com.sketch.search.binarysearch.BinarySearch;
3+
import com.sketch.sort.selectionsort.SelectionSort;
4+
5+
import java.util.Arrays;
6+
import java.util.Random;
47

58
public class Main {
69
public static void main(String[] args){
7-
int[] sortedArray = { 1, 2, 3, 5, 7, 9, 11, 14, 17, 26, 18, 37, 42, 43, 44, 47, 48, 49, 78, 227, 5556, 8976 };
8-
int valueToFind = 18;
10+
int[] unsortedArray = new int[20];
11+
Random random = new Random();
12+
for(int i = 0; i < unsortedArray.length; i++){
13+
unsortedArray[i] = random.nextInt(20);
14+
}
15+
16+
int[] unsortedArrayResult = new int[unsortedArray.length];
17+
System.arraycopy(unsortedArray, 0, unsortedArrayResult, 0, unsortedArray.length);
918

10-
int binarySearchIndex = BinarySearch.searchRecursive(sortedArray, valueToFind, 0, sortedArray.length - 1);
19+
unsortedArrayResult = SelectionSort.sort(unsortedArrayResult);
1120

12-
System.out.println("Expected Value Index: 20");
13-
System.out.println("Actual Value Index: " + binarySearchIndex);
21+
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArray));
22+
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArrayResult));
1423
}
1524
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.sketch.sort.selectionsort;
2+
3+
public class SelectionSort {
4+
public static int[] sort(int[] unsortedArray){
5+
if(unsortedArray.length == 1){
6+
return unsortedArray;
7+
}
8+
9+
int length = unsortedArray.length;
10+
11+
for (int i = 0; i < length - 1; i ++){
12+
int min = unsortedArray[i];
13+
int minIndex = i;
14+
for(int j = i + 1; j < unsortedArray.length; j++){
15+
if(unsortedArray[j] < min){
16+
min = unsortedArray[j];
17+
minIndex = j;
18+
}
19+
}
20+
swap(unsortedArray, i, minIndex);
21+
}
22+
23+
return unsortedArray;
24+
}
25+
26+
private static void swap(int[] array, int a, int b){
27+
int temp = array[a];
28+
array[a] = array[b];
29+
array[b] = temp;
30+
}
31+
}

0 commit comments

Comments
 (0)