Insertion Sort builds the sorted list one element at a time by inserting elements into their correct positions.
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
Insertion sort performs well on small or nearly sorted data, making it suitable for small applications.
Take quizzes related to this topic and see where you stand!
Start Quiz Now