Sort a given set of n integer elements using Selection Sort method. analysis worst case average case and best case.

1] Sort a given set of n integer elements using Selection Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. Demonstrate using C++/Java how the brute force method works along with its time complexity analysis: worst case, average case and best case.

PROGRAM :-

import java.util.Scanner;
import java.util.Random;

public class selection_sort {
    public static void main(String args[])

    {
        int i, j, temp;

        System.out.println("Enter array size");
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] arr = new int[500];

        Random generator = new Random();

        for (i = 0; i < n; i++) {
            arr[i] = generator.nextInt(100);
        }

        System.out.println("Array before sorting");

        for (i = 0; i < n; i++) {
            System.out.println(arr[i] + " ");
        }

        long startTime = System.nanoTime();

        for (i = 0; i <= n - 2; i++)

        {
            int min = i;

            for (j = i + 1; j <= n - 1; j++)

            {

                if (arr[j] < arr[min])
                    min = j;

            }

            temp = arr[i];

            arr[i] = arr[min];

            arr[min] = temp;

        }

        long stopTime = System.nanoTime();

        long elapseTime = (stopTime - startTime);

        System.out.println("Time taken to sort array is:" + elapseTime + "nanoseconds");

        System.out.println("Sorted array is");

        for (i = 0; i < n; i++)
            System.out.println(arr[i]);

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *