Selection sorting is conceptually the most simplest sorting algorithm. This algorithm first finds the smallest element in the array and exchanges it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continues in this way until the entire array is sorted.
Note: Selection sort is an unstable sort i.e it might change the occurrence of two similar elements in the list while sorting. But it can also be a stable sort when it is implemented using linked list data structures.
How Selection Sorting Works
Sorting using Selection Sort Algorithm
void selectionSort(int a[], int size) { int i, j, min, temp; for(i=0; i < size-1; i++ ) { min = i; //setting min as i for(j=i+1; j < size; j++) { if(a[j] < a[min]) //if element at j is less than element at min position { min = j; //then set min as j } } temp = a[i]; a[i] = a[min]; a[min] = temp; } }
Complexity Analysis of Selection Sorting
Worst Case Time Complexity : O(n2) Best Case Time Complexity : O(n2) Average Time Complexity : O(n2) Space Complexity : O(1)
0 Comments:
Post a Comment