Course contentsShow
← C
Lesson 1049 of 1,21914. Data Structures in CFree lesson

Insertion Sort: Shifting elements

Insertion Sort: Shifting elements

What you'll learn: How to create space for a value by moving existing elements to the right, one by one.

The card player's logic

Imagine you are playing a card game. You hold a sorted hand of cards, and you pick up a new one: a 7. To put it in the right spot, you don’t just swap it with another card. Instead, you look at your cards from right to left. If a card is larger than 7, you slide it one position to the right to open up a gap. You keep sliding cards until you find the perfect "hole" where the 7 belongs.

In C, we call this process shifting. Unlike a swap (which just trades two spots), a shift moves an entire wall of data to make room for a single value.

How shifting works in code

To shift elements, we first save our "target" value in a temporary variable. Then, we use a while loop to look at the elements to its left. As long as those elements are larger than our target, we copy them one position to the right.

int arr[] = {2, 5, 8, 12, 7}; // 7 is our 'target' at index 4
int target = arr[4]; 
int j = 3; // Start comparing with the element to the left (12)

// While we aren't at the start AND the element is bigger than 7
while (j >= 0 && arr[j] > target) {
    arr[j + 1] = arr[j]; // Copy the element to the right
    j--;                 // Move our focus left
}

// After the loop, j + 1 is the empty slot
arr[j + 1] = target; 

Why we shift instead of swap

If we simply swapped the 7 with the 12, our array would become {2, 5, 8, 7, 12}. While the 12 moved to the end, the 7 is still in the wrong place relative to the 8!

Shifting ensures that we don't just move one item; we preserve the sorted order of everything behind the target. We treat the array like a row of books on a shelf: to fit a new book in the middle, you must push all the books to its right down by one inch. The while loop acts as your hand, pushing each "larger" value out of the way until the correct slot is revealed.

Key takeaway

Shifting creates a "hole" in the array by copying larger elements one index to the right, allowing a value to be inserted into its perfectly sorted position.