Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 540
Nanda Ardianto Avatar asked Sep 27 '22 17:09

Nanda Ardianto


People also ask

Can selection sort be in descending order?

A descending order selection sort could also be defined. In this case the only change to the algorithm would be that instead of selecting the smallest object from the input list in step 3.1, the largest item would be selected. The final result would be a list sorted in descending order, from largest to smallest.

Is selection sort ascending or descending?

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.

How do you do a selection sort?

Algorithm and Pseudocode of a Selection Sort AlgorithmStep 1: Set Min to location 0 in Step 1. Step 2: Look for the smallest element on the list. Step 3: Replace the value at location Min with a different value. Step 5: Continue until the list is sorted.

Is selection sort divide and conquer?

Bubble sort may also be viewed as a k = 2 divide- and-conquer sorting method. Insertion sort, selection sort and bubble sort divide a large instance into one smaller instance of size n - 1 and another one of size 1. All three sort methods take O(n2) time.


1 Answers

You just need to negate the compareTo method

if(data[sweep].compareTo(data[minIndex]) > 0)
    minIndex=sweep;
like image 115
Sleiman Jneidi Avatar answered Nov 02 '22 11:11

Sleiman Jneidi