Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11 // this is the initial, starting state of the array
11 25 12 22 64 // sorted sublist = {11}
11 12 25 22 64 // sorted sublist = {11, 12}
11 12 22 25 64 // sorted sublist = {11, 12, 22}
11 12 22 25 64 // sorted sublist = {11, 12, 22, 25}
11 12 22 25 64 // sorted sublist = {11, 12, 22, 25, 64}
Selection sort animation. Red is current min. Yellow is sorted list. Blue is current item.
(Nothing appears changed on these last two lines because the last two numbers were already in order) .
In Simple Word :- We Store Array First Element to Temporary Variable Call Min and Compare Min To Array Next Element ,If array is Next element is small then Min Become Next smaller element And Swap .Repeat this process until All Element Not Sorted .
Swapping :-
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
Complexity :-
Worst-case performance--> О(n^2)
Best-case performance--> О(n^2)
Average performance--> О(n^2)
Worst-case space complexity--> О(n) Total, O(1) Auxiliary .
Note :- In All Cases Selection Sort Complexity is Always O(n^2) .
Question :-
Why Use Selection Sort When Complexity Is O(n^2) in all Case ?
Answer :- The Best thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation .
Output:
Enter The Size Of Array
10
Enter The Element Of Array
1 2 3 4 5 10 9 8 7 6
SORTED ARRAY IN ACCENDING ORDER
1 2 3 4 5 6 7 8 9 10
SORTED ARRAY IN DESCENDING ORDER
10 9 8 7 6 5 4 3 2 1
need an explanation for this answer? contact us directly to get an explanation for this answer