-1

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 
cnmesr
  • 345
  • 3
  • 11
  • 2
    If your current output does not match your desired output, and you don't know why, then it's time to start debugging. If you're not sure how to go about doing this, then please have a look at: [How to Debug Small Programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). It won't solve your direct problem, but it will give you steps that you can follow that should help you solve it yourself, or even if that is not successful, then at least help you to better isolate your problem so that your question can be more focused and easier to answer. – Hovercraft Full Of Eels Jul 08 '17 at 20:14
  • 1
    Why do you feel it necessary to use a second array? At the end of the described procedure, A will be sorted. – rici Jul 08 '17 at 22:51
  • @rici I didn't know that. I just read about it and tried to create a code from the text I read (I can also remember I read that it's an "in place" algorithm but back then I didn't know what it meant). But after reading through the answers and comments, I realized it was useless to use a second array and what "in place" actually means ^^ – cnmesr Jul 08 '17 at 22:53
  • Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Jul 12 '17 at 08:36

6 Answers6

3

"Smallest element found, now switch this element with the first element of the unsorted array A". So, you must switch the first element with the smallest element. You can use the code like this:

static int findMIN(int[] A, int c) {
    int first = c; // The first element's id
    int id = c; // An id of the smallest element
    int x = A[c];
    while(c<A.length) {
        if(x>A[c]) {
            x=A[c];
            id = c;
        }
        c++;
    }

    // Switching the first element with the smallest element
    int tmp = A[first];
    A[first] = A[id];
    A[id] = tmp;

    return x;
}

It works perfectly. Also check @VidorVistrom's answer, if you don't understand why does your code work as it works.

Ihor Dobrovolskyi
  • 1,241
  • 9
  • 19
3

Why doesn't my selection sort algorithm do what it's supposed to (java)?

Lets see whats happening:

   c         A[c]       Returned X
-----------------------------------
   0          9            0(Since minElement is 0 with index >= 0)
   1          6            0(Since minElement is 0 with index >= 1)
   2          1            0(Since minElement is 0 with index >= 2)
   3          3            0(Since minElement is 0 with index >= 3)
   4          0            0(Since minElement is 0 with index >= 4)
   5          4            2(Since minElement is 2 with index >= 5)
   6          2            2(Since minElement is 2 with index >= 6)
Pushan Gupta
  • 3,697
  • 5
  • 23
  • 39
3

First, fix your findMIN, you should return the index of the minimum element (and compare the element at the current value to the minimum). Like,

static int findMIN(int[] A, int c) {
    int x = c;
    for (; c < A.length; c++) {
        if (A[c] < A[x]) {
            x = c;
        }
    }
    return x;
}

Then I would use a swap method, like

static void swap(int[] A, int a, int b) {
    if (a != b) {
        int t = A[a];
        A[a] = A[b];
        A[b] = t;
    }
}

Finally, tie it together like

public static void main(String[] args) {
    int[] myArray = { 9, 6, 1, 3, 0, 4, 2 };

    for (int i = 0; i < myArray.length; i++) {
        swap(myArray, i, findMIN(myArray, i));
    }
    System.out.println(Arrays.toString(myArray));
}

And, I get

[0, 1, 2, 3, 4, 6, 9]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

Your findMIN function always returns min value of the myArray starting from ith index. You are getting first 5 values 0 because, myArray[4] contains 0. Then for the last two digits you are getting 2 because from myArray[5] to myArray[6] min value is 2.

Just after finding min value in your findMIN function you should swap this value with the initial index 'c' you passed into the function. In that case next time when you call findMIN function it will exclude that min value you got earlier.

As you did not want to see any implementation I try to say the solution in words. Hope it helps you.

Mazedul Islam
  • 1,543
  • 1
  • 11
  • 15
1

You don't swap elements when you find the minimum. Try this fix

static int findMIN(int[] A, int c) {
    int x = A[c];
    int min_index = c;
    for(int i=c; i<A.length; i++) {
        if(x>A[i]) {
            x=A[i];
            min_index = i;
        }
    }
    A[min_index] =  A[c];
    A[c] = A[min_index];
    return x;
}

Also know that Selection Sort is an in place algorithm, so you don't need a separate empty array to sort.

Ratacand
  • 120
  • 10
1
public class Selectionsort {

    public static void main(String[] args) {
        int[] myArray = {9, 6, 1, 3, 0, 4, 2};

        for (int i = 0; i < myArray.length; i++) {

            int pos = findMIN(myArray, i);
            int element = myArray[pos];

            //swap 
            int temp = myArray[i];
            myArray[i] = element;
            myArray[pos] = temp;

        }

        System.out.println(Arrays.toString(myArray));
    }

    //get the postion 
    static int findMIN(int[] A, int c) {
        int x = A[c];
        int position = c;
        while (c < A.length) {
            if (x > A[c]) {
                x = A[c];
                position = c;
            }
            c++;
        }
        return position;
    }
}
JGarnica
  • 203
  • 2
  • 13