javarecursionpseudocodeselection-sort

Recursive Selection sort Java


I've been looking for a recursive selection sort, using only 2 parameters:

Example: SelectionSort(array[] a, int k) with a being {6,3,5,7,2} and k being 2 will sort the first 3 elements, and will keep the last elements untouched.

I was thinking about starting with an if-statement for k being 0, and if that was the case, it would just return the array as it is, since you cant sort an array of size 1. Something like:

public int[] sort(int[] a){
    a = selectionSort(a, n-1);
    return a;
}

public int[] selectionSort(int[] a, int k){
    if (k = 0){
        return a;
    }
    else{
        selectionSort(a, k-1 );
               ... (part i really don't know)
}

I have no clue how to do the 'else' part since I only know that it has to call the method again. I'm not allowed to create other methods. I also need to make sure I use exactly 2 parameters, nothing more, nothing less.

I have to work it out in pseudocode, but I understand some Java, so if someone could help me by using either pseudo, or Java, it would be so helpful


Solution

  • First some remarks to your code:

    You already figured out the first part. Here it is how you can do the second part in pseudo code:

    public void selectionSort(int[] a, int k) {
        if (k == 0) {
            return;
        }
        else {
            selectionSort(a, k-1 );
            find x such that a[x] is the smallest of a[k] ... a[a.length - 1]
            if (a[k-1] > a[x]) {
                swap a[k-1] and a[x]
            }
        }
    }
    

    I'm sure you are able to refine the pseudo code to real Java code.