How to Insert Into Sorted Array – Free C Programming Course

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Arrays

Insert Into Sorted Array

Learn how to insert an element in a sorted array in C by shifting items right, and keep the order intact. A hands-on lesson from our free C tutorial.

How do you insert an element in a sorted array in C without sorting the whole array again? You find the right gap by walking from the right-hand end, shifting larger values one slot to the right, and dropping the new value into the hole. This lecture of our free C programming course explains that idea slowly, shows it in an inline diagram, and gives you a tested function you can reuse in embedded C programming, for example to keep a small list of event timestamps in order.

What You Will Learn

  • Why you can insert into a sorted array without a full re-sort
  • How the right-to-left shifting loop works, one step at a time
  • How to write a reusable insert_sorted() function
  • How to protect against a full buffer
  • Why the order of the two loop conditions is important
  • How many shifts are needed for the best and worst case

Prerequisites

  • The previous lecture on bubble sort in C, or at least comfort with array loops
  • Passing an array and its length to a function
  • while loops and the logical AND operator

The Problem: Keep the Array Sorted

Suppose you keep a log of up to eight packet sequence numbers, always in ascending order. The array currently holds five items and has room for three more. A new value 20 arrives. If you simply wrote it at the end, the order would break. If you called a sort function, you would do far more work than needed, because five of the six items are already in the right relative order. The better plan is to open a gap exactly where 20 belongs.

Precondition

This technique only works if the array is already sorted and has at least one free slot at the end. Inserting into an unsorted array with this method gives meaningless results.

How to Insert an Element in a Sorted Array in C

The algorithm has four short steps:

  1. Start at the last used element, index n - 1.
  2. While that element is greater than the new value, copy it one slot to the right and move left.
  3. Stop when you reach an element that is not greater than the new value, or when you fall off the left edge.
  4. Write the new value into the slot just to the right of where you stopped.

Walking from the right is the clever part. Each shift copies into a slot that is already free or already copied, so no value is overwritten before it is saved.

Insert 20 into a sorted array: shift, shift, place
Legend
sorted itemnew valuefree slot or gap
Start (n = 5)
512192733freefreefree
33 > 20, shift
5121927gap33freefree
27 > 20, shift
51219gap2733freefree
19 > 20? No, stop
51219gap2733freefree
Place 20 (n = 6)
51219202733freefree

Insert Element in Sorted Array: C Program

The code wraps the algorithm in a function that returns the new item count, or -1 when there is no room. Returning a status instead of silently writing past the end is the habit that keeps embedded C programs safe.

#include <stdio.h>

#define CAPACITY 8

static void print_array(const int a[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%3d", a[i]);
    printf("\n");
}

/* Insert value into a sorted array holding n items.
   Returns the new item count, or -1 if the buffer is full. */
static int insert_sorted(int a[], int n, int cap, int value)
{
    if (n >= cap)
        return -1;

    int i = n - 1;
    while (i >= 0 && a[i] > value) {
        a[i + 1] = a[i];   /* shift one slot right */
        i--;
    }
    a[i + 1] = value;      /* drop the value into the gap */
    return n + 1;
}

int main(void)
{
    int log[CAPACITY] = {5, 12, 19, 27, 33};
    int count = 5;
    int tests[] = {20, 1, 40, 12, 8, 3, 50};

    printf("Before    :");
    print_array(log, count);

    for (int t = 0; t < 7; t++) {
        int r = insert_sorted(log, count, CAPACITY, tests[t]);
        if (r < 0) {
            printf("Insert %2d : buffer full, rejected\n", tests[t]);
            continue;
        }
        count = r;
        printf("Insert %2d :", tests[t]);
        print_array(log, count);
    }
    return 0;
}

Reading the code line by line

  • n is the number of items currently stored, cap is the buffer size. Never confuse the two.
  • if (n >= cap) return -1; rejects the insert before touching memory.
  • i = n - 1 points at the last stored item.
  • while (i >= 0 && a[i] > value) shifts while there is something left to compare and that something is bigger.
  • a[i + 1] = a[i]; copies one slot right. The slot at i + 1 is always free at that moment.
  • After the loop, a[i + 1] = value; fills the gap. If the loop never ran, i + 1 equals n, so the value is appended.

Build and run

gcc -Wall -Wextra -std=c11 -o insert_sorted insert_sorted.c
./insert_sorted

Expected output:

Before    :  5 12 19 27 33
Insert 20 :  5 12 19 20 27 33
Insert  1 :  1  5 12 19 20 27 33
Insert 40 :  1  5 12 19 20 27 33 40
Insert 12 : buffer full, rejected
Insert  8 : buffer full, rejected
Insert  3 : buffer full, rejected
Insert 50 : buffer full, rejected

The first three inserts succeed: 20 lands in the middle, 1 lands at the very front, and 40 is appended at the end. After that the buffer holds eight items, so the next four inserts are rejected cleanly instead of corrupting memory.

Why the Order of the Conditions Matters

Look again at the loop condition: i >= 0 && a[i] > value. The bounds check comes first. C evaluates && from left to right and stops as soon as the left side is false (short-circuit evaluation). When the new value is smaller than everything in the array, i eventually becomes -1. Because i >= 0 is now false, a[i] is never evaluated, so we never read a[-1].

Warning: If you swap the two conditions and write a[i] > value && i >= 0, the program reads a[-1] before checking i. That is undefined behaviour. It often “works” on a PC and then fails on a different compiler or a microcontroller. Always check the index before using it.

Cost of Each Insert

Where the value belongsShifts neededExample (n = 5)
At the end (largest so far)0Insert 40: no shift
In the middleNumber of items larger than itInsert 20: 2 shifts
At the front (smallest so far)n (worst case)Insert 1: 5 shifts
Equal to an existing valueOnly items strictly larger shiftInsert 12: new 12 goes after the old 12

Because the loop uses a strict “greater than”, an equal value stops the shifting and is placed after the existing equal values. That keeps older entries before newer ones, which is the stable behaviour you usually want in a log.

Real-World Uses in Embedded C

  • Timer lists: keep software timers sorted by expiry time so the next due timer is always at index 0.
  • Top-N tracking: keep the best 8 readings seen so far in a small sorted buffer.
  • Event queues with priority: insert an event into a small array ordered by priority.
  • Sorted lookup tables: add one calibration point without rebuilding the entire table.

Common Mistakes and Troubleshooting

SymptomLikely causeFix
New value overwrites an existing itemShifted from left to right instead of right to leftAlways start at index n – 1 and move left
Crash or garbage when inserting a tiny valueIndex check placed after the array accessPut i >= 0 first
Last element lostForgot to increase the item countReturn or store n + 1
Memory corruption after many insertsNo full-buffer checkCompare n with the capacity first
Output not sortedArray was not sorted before the first insertSort the initial data once, or start empty

Best Practices

  • Pass the capacity into the function. Do not rely on a global.
  • Return a clear status when the buffer is full.
  • Test three insert positions every time: front, middle, end.
  • Performance: each insert costs up to n copies. For hundreds of items, a different structure (a heap or a linked list) is a better fit.
  • Security and safety: an unchecked insert is a classic buffer overflow. Treat the capacity check as mandatory, especially when the value comes from outside the device.

Summary and Key Takeaways

  • To insert an element in a sorted array in C, shift larger items one place right, starting from the right end.
  • Stop at the first item that is not larger, then write the new value into the gap.
  • Check i >= 0 before reading a[i].
  • Reject the insert when the array is full.
  • Cost is between 0 and n shifts per insert.
  • Whenever you need to insert an element in a sorted array in C, remember the pattern: check capacity, shift right-to-left, place, increase the count.

Conclusion

You can now insert an element in a sorted array in C safely and explain every line. Knowing how to insert an element in a sorted array in C also gives you a clean way to keep live data ordered without paying for a full sort each time. This single function is the engine of the next lecture. Insertion sort is nothing more than inserting each element of an unsorted array into the sorted part on its left, one by one. If you want free embedded C programming practice, try changing the function so that it sorts in descending order.

Frequently Asked Questions

Do I need to re-sort the array after inserting?

No. If the array was sorted before, shifting and placing the new value keeps it sorted.

Why do we shift from the right instead of the left?

Shifting from the right copies each value into a slot that is already free, so nothing is overwritten before it is saved.

What happens if the array is full?

Writing would go past the end of the array. The example function checks the item count and returns -1 instead.

What is the time complexity of inserting into a sorted array?

O(n) in the worst case, because up to n elements may need to move.

Can I use binary search to find the position faster?

Yes, you can find the position in O(log n) comparisons, but you still need to shift elements, so the total cost remains O(n).

Where do duplicates go?

With a strict greater-than test, a duplicate is placed after the existing equal values.

Is this the same as insertion sort?

It is the core step. Insertion sort repeats this insert for every element of an unsorted array.

Continue Your Free C Programming Course

Next up: insertion sort in C. Follow our free embedded C course to build real firmware skills step by step.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *