A sorting algorithm which splits the input array in 2 parts, the sorted part and the unsorted part. In every iteration, the minimum element is found from the unsorted array and appended to the sorted array.
Characteristic | Value | Notes |
---|---|---|
Average Time Complexity | O(n2) | Same for worst case |
Best Time Complexity | O(n2) | For a sorted array as well |
Space Complexity | O(1) | No extra storage required |
selection_sort()
function is pretty simple, it works with 2
iterators:
itr_1
: Holds the index of the end of
sorted array after which the the unsorted array will begin
itr_2
: Traverses the unsorted array to find the
smallest element from the unsorted array.
itr_2
in the unsorted array and find the minimum
value among them
// function for selection sort
void selection_sort(int arr[], int n) {
// i = itr_1 , j = itr_2
for(int i = 0; i < n - 1; ++i) {
int min_idx = i;
// traverse the un-sorted array
for(int j = i + 1; j < n; ++j) {
if(arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// swap the values
swap(arr[i], arr[min_idx]);
}
return;
}