How to cancel sorting sort

I am trying to write this sorting selection from high to low, and I'm not quite sure how to do this. I am 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 I'm trying to change it is because the sort is sorted through the rest of the array, looking for the minimum value, and then swaps it to the foreground. I want to change the algorithm so that it also looks for the maximum value in the remainder and swaps it back, so that it simultaneously creates a sorted list in front and back.

All help would be appreciated :)

+5
source share
2 answers

You just need to cancel the compareTo method

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

Select a sort, find the smallest remaining element in each iteration, and place it in the right place. Instead, you want to find the largest remaining element. The easiest way to do this is to simply flip the selection condition. Instead:

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

You should use:

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

All Articles