Search code examples
javaarraysalgorithmselection-sort

Reverse SelectionSort to sort array


My selection sort here runs through the remaining part of the array, looking for the minimum value and then swaps it to the front.I want to change the algorithm so that it also looks for the maximum value in the remaining part, and swaps it to the back, so that it builds up a sorted list from the front and the back at the same time.

public  void selectionSort(String[ ] data){
    // for each position, from 0 up, find the next smallest item 
    // and swap it into place
    for (int place=0; place<data.length-1; place++){
        int minIndex = place;
        for (int sweep=place+1; sweep<data.length; sweep++){
            if (data[sweep].compareTo(data[minIndex]) < 0)
                minIndex=sweep;
        }
        swap(data, place, minIndex);
    }
}

I have another method that checks if the array has been sorted or not so the solution has to go through that

public boolean testSorted(String[] data) {
    for (int i=1; i<data.length; i++){
        if (data[i].compareTo(data[i-1]) < 0)
            return false;
    }
    return true;
}

Any help would be appreciated, I've been going at it for hours. I'm new to this and I really wanna get it. Thanks

This is what I have tried:

public  void selectionSort2(String[ ] data){
    // for each position, from 0 up, find the next smallest item 
    // and swap it into place
    for (int place=0; place<data.length-1; place++){
        int minIndex = place;
        for (int sweep=place+1; sweep<data.length; sweep++){
            if (data[sweep].compareTo(data[minIndex]) > 0)
                minIndex=sweep;
        }
        swap(data, place, minIndex);
    }
}

Solution

  • You only need to change and it will sort in reverse orger:

    In method selectionSort()

    if (data[sweep].compareTo(data[minIndex]) > 0)
    

    and in method testSorted()

    if (data[i].compareTo(data[i-1]) > 0)
    

    But if you need to change order, so that it must start sort from back of array, it will look as:

        public static void selectionSort(String[ ] data){
        // for each position, from 0 up, find the next smallest item
        // and swap it into place
        for(int place=data.length-1; place >= 1; place--){
            int maxIndex= place;
            for(int sweep = place-1; sweep >= 0; sweep--){
                if(data[sweep].compareTo(data[maxIndex]) > 0){
                    maxIndex = sweep;
                }
            }
            swap(data, place, maxIndex);
        }