Nanda Ardianto
Nanda Ardianto

Reputation: 367

How to reverse selection sort

I'm trying to write this selection sort from high to low and I'm not quite sure how to do that. I'm pretty new to sorting algorithms.

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);
    }
}

The reason to why I'm trying to change it is that the 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.

All help would be appreciated :)

Upvotes: 5

Views: 960

Answers (2)

Mureinik
Mureinik

Reputation: 311843

A select sort find the smallest remaining item in each iteration and puts in the right place. Instead, you want to find the largest remaining item. The simplest way of doing this is by just flipping the selection condition. Instead of:

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

You should use:

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

Upvotes: 2

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

You just need to negate the compareTo method

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

Upvotes: 2

Related Questions