insertion sort cpp

Insertion sort is a simple sorting algorithm that works by dividing the input array into a sorted and an unsorted region. It repeatedly takes elements from the unsorted region and inserts them into their correct position in the sorted region.

Here is the step-by-step explanation of the insertion sort algorithm in C++:

  1. Start with the second element of the array, assuming the first element is already sorted.
  2. Take the current element and store it in a temporary variable.
  3. Compare the current element with the elements in the sorted region, moving from right to left.
  4. If the current element is smaller than the element being compared, shift the compared element one position to the right.
  5. Repeat step 4 until you find an element that is smaller than or equal to the current element.
  6. Insert the current element in the position found in step 5.
  7. Repeat steps 2-6 for the remaining elements in the unsorted region.
  8. Continue until all elements in the array are sorted.

Here is an example implementation of the insertion sort algorithm in C++:

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;
    }
}

In this implementation, the insertionSort function takes an array arr and its size n as input. It performs the insertion sort algorithm on the array, sorting it in ascending order. The algorithm starts from the second element (index 1) and iterates through the array, comparing each element with the elements in the sorted region. It shifts elements to the right until it finds the correct position to insert the current element.

I hope this explanation helps! Let me know if you have any further questions.