Question

Write a simple Java program that that sorts the following array, 5 7 4 9 8...

Write a simple Java program that that sorts the following array, 5 7 4 9 8 5 6 3, using a selection sort algorithm. What is the Big O of the algorithm?

0 0
Add a comment Improve this question Transcribed image text
Answer #1
public class Selection_sort {
    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void selectionSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            int lowindex = i;
            for (int j = array.length - 1; j > i; j--)
                if (array[j] < (array[lowindex])) {
                    lowindex = j;
                }
            swap(array, i, lowindex);
        }
    }

    public static void main(String[] args) {
        int arr[] = {5, 7, 4, 9, 8, 5, 6, 3};
        selectionSort(arr);
        for(int i = 0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
    }
}

3 4 5 5 6 7 8 9 

First for loop is running for i values from 0 to n with an increment of 1
So, it runs for O(n) times
Inner for loop is running for j values from n to i with a decrement of 1
So, At max it runs max of O(n) times
So, total time complexity = O(n*n) = 

​​​​​​​

Add a comment
Know the answer?
Add Answer to:
Write a simple Java program that that sorts the following array, 5 7 4 9 8...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT