In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).
I won't copy paste the explanation but rather depict it (to check if I understood it):
-We have one unsorted array A and an empty array B (which has the same size as A)
-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A
-Put the first element (=smallest element of array A) into the array B
-Repeat till we are done with every element of A
I tried to code that in Java:
public class Selectionsort{
public static void main(String[] args) {
int[] myArray = {9,6,1,3,0,4,2};
int[] B = new int[myArray.length];
for(int i=0; i<myArray.length; i++) {
B[i]=findMIN(myArray, i);
}
}
static int findMIN(int[] A, int c) {
int x = A[c];
while(c<A.length) {
if(x>A[c]) {
x=A[c];
}
c++;
}
return x;
}
}
But I get a weird output:
0 0 0 0 0 2 2