Answer to Question #191627 in Java | JSP | JSF for Haider

Question #191627

Write a function to sort array elements using Selection sort in Descending order .also Compute the best case and worst case time complexity of selection sort.


1
Expert's answer
2021-05-11T07:05:56-0400
import java.util.Arrays;

public class Main {
    public static void selectionSort(int[] array) {
        int max;
        int tmp;
        for (int i = 0; i < array.length; i++) {
            max = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[max] < array[j]) {
                    max = j;
                }
            }
            tmp = array[i];
            array[i] = array[max];
            array[max] = tmp;
        }
    }

    public static void main(String[] args) {
        int[] array = {1, 5, 2, 4, 8, 3, 5, 1, 7, 0, 8};
        System.out.println(Arrays.toString(array));
        selectionSort(array);
        System.out.println(Arrays.toString(array));
    }
}

The best and worst time complexity will have complexity O(n^2) since in both cases the number of iterations will be equal to the sum of 1 + 2 + 3 ... (n-3) + (n-2) + (n-1), which is an arithmetic progression that equals ((1 + (n - 1)) / 2) * (n - 1) = (n^2 - n) / 2 = O(n^2).



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS