Home > Mobile >  How to write a selectionSort method going in Descending order?
How to write a selectionSort method going in Descending order?

Time:11-10

Hello there! At the moment, I am just a tad bit confused with my code. I'd like to move my array in descending order. This sounds very simple but for some reason I cannot wrap my head around this method. Currently, this is a selectionSort method I wrote that goes directly in ascending order. I'm not sure where to start when it comes to descending order.. as to how to reverse the equations, I usually end up overflowing since it's supposed to be using the original ".length" of the array.

Thank you very much for any help!


int[] arr = {5, 3, 2, 44, 1, 75, 23, 15};

private static void descendingSort (int[] arr) {

        for ( int i = 0; i < arr.length - 1; i  ) {
            int smallestIndex = i;

            for ( int j = i   1; j < arr.length; j  ) {
                //searching for smallest...
                //if statement declaring if arr is smaller than the index[0] 
                if (arr[j] < arr[smallestIndex]) { 
                    //now it has changed to pickle because it has swapped. thx u 
                    smallestIndex = j;
                }
            }

        }
}

CodePudding user response:

If you want to solve the problem fast, here's how you approach it. Notice we just change a few lines.

Specifically ...

  1. We still find the smallest element
  2. We put it in the back and not the front
  3. The iteration order in both loops is back-to-front and not front-to-back

An easier way to implement this would be to just sort the elements in ascending order and then just reverse the array.

 void selectionSortDescending(int arr[])
    {
        int n = arr.length;

        // Start by finding the smallest element to put in the very back
        // One by one move boundary of unsorted subarray
        for (int i = n-1; i >= 0; i--)
        {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i-1; j >= 0; j--)
                if (arr[j] < arr[min_idx])
                    min_idx = j;
 
            // Swap the found minimum element with the last element
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
  • Related