A sorting algorithm which splits the input array in 2 parts, the sorted part and the unsorted part. In every iteration, the last element of the unsorted array is placed at its correct position in the sorted array.
Characteristic | Value | Notes |
---|---|---|
Average Time Complexity | O(n2) | Same for worst case |
Best Time Complexity | O(n) | For a sorted array |
Space Complexity | O(1) | No extra storage required |
bubble_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 sorted array to find the correct
position of the unsorted element by shifting all the elements
greater than it to the right
itr_2
to the left and shift the element to the right
if its value is greater than the unsorted element.
// function for insertion sort
void insertion_sort(int arr[], int n) {
// i = itr_1 , j = itr_2
for(int i = 1; i < n; ++i) {
int unsorted = arr[i];
int j = i - 1;
// traverse the sorted array
while(j >= 0 && arr[j] > unsorted) {
arr[j + 1] = arr[j];
}
j++;
arr[j] = unsorted;
}
return;
}