AI Exp 3
AI Exp 3
Assignment No: 03
Title: Implement Greedy search algorithm for Selection Sort.
We will perform N-1 iterations on the array (N is the number of elements in the
array). In iteration i (1≤i≤N-1):
● We will traverse the array from the ith index to the end and find the smallest
number among these elements. Note that if there are two smallest elements of
the same value, we choose the one with the lower index.
● We will swap this smallest element with the i element.
● Hence at the end of the ith iteration, we have found the ith smallest number,
and placed it at the ith position in the array.
In the (N-1)th iteration, we will place the (N-1)th smallest element, which is the 2nd largest
element in the array, at the second last position. This will leave us with one element which
would already be at its correct place. This completes our sorting! Selection Sort Algorithm.
Running Time of Selection Sort
Let's assume that we are sorting N elements of a given array using Selection Sort.
To complete one iteration, we traverse a part of the array (from index i to the end) exactly once
(while keeping track of the smallest element encountered so far). Since the longest length we
ever traverse in any given iteration is N (in the first iteration when i=1 -> from first to last
element), time complexity of completing one iteration is O(N).
In Selection Sort, we run N iterations, each of which takes O(N) time. Hence overall time
complexity becomes O(N*N).
Questions:
Conclusion:
In This way we have studied how to sort, unsorted list of numbers using selection sort.