DAA 2022-23 Manual
DAA 2022-23 Manual
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.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
Output:
1.2E+09
1E+09
800000000
600000000
400000000
200000000
0
1 2 3 4
Worst Case: The worst case occurs when the input array is in reverse order. In
this case, selection sort performs n-1 comparisons for the first element, n-2 for
the second, and so on. This results in a total of (n-1) + (n-2) + ... + 1 = n(n-
1)/2 comparisons, which is in the order of O(n^2).
Average Case: The average case time complexity of selection sort is also
O(n^2). This is because, on average, the algorithm needs to perform
approximately the same number of comparisons and swaps as in the worst case.
Best Case: The best case occurs when the input array is already sorted. In this
case, selection sort still performs n-1 comparisons but makes only 0 or n-1
swaps. The number of swaps can be reduced by using an additional variable to
track the minimum element's index instead of swapping elements during each
iteration. The best case time complexity is still O(n^2) because the number of
comparisons remains the same.