Search code examples
javaarraysalgorithmsortingselection-sort

Sorting an array using Selection Sort


I have implemented a code to sort this array using Selection Sort. The code seems to be fine, but it doesn't sort the array perfectly. This is the array to be sorted, {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2}

Here is the code I implemented;

public class Main {

    public static void main(String[] args) {
        int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
        System.out.println("Unsorted Array: \t");
        StringBuffer sb = new StringBuffer();
        for (Object s : arr) {
            sb.append(s);
            sb.append(" ");
        }
        String str = sb.toString();
        System.out.println(str);


        selectionSort(arr);
        System.out.println("Sorted Array: \t");
        printArray(arr);
    }

    public static void selectionSort(int[] arr) {
        int n = arr.length;
        // one by one move boundary of unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // find the minimum element in unsorted array
            int min = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
                }
                //swapping the found min value with the first element
                int temp = arr[min];
                arr[min] = arr[i];
                arr[i] = temp;
            }
        }
    }

    public static void printArray(int[] arr) {
        StringBuffer sb = new StringBuffer();
        for (Object s : arr) {
            sb.append(s);
            sb.append(" ");
        }
        String str = sb.toString();
        System.out.println(str);
    }
}

And here is the output I received;

enter image description here

I have no idea why it is not sorting out properly, Would love to have some help.


Solution

  • The swap comes after the inner loop. Like,

    public static void selectionSort(int[] arr) {
        int n = arr.length;
        // one by one move boundary of unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // find the minimum element in unsorted array
            int min = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
                }
            }
            // swapping the found min value with the first element
            int temp = arr[min];
            arr[min] = arr[i];
            arr[i] = temp;
        }
    }
    

    Just changing that (and adding a printArray) I get

    Unsorted Array:     
    [20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2]
    Sorted Array:   
    [2, 5, 6, 7, 14, 17, 19, 20, 22, 39, 42, 46, 47, 48, 51]