Kodewick
Start learning →
Inserting and deleting in an array5 / 50

Inserting and deleting in an array

Lesson 5 of 50 · Part 2 · Arrays and linked lists · about 15 minutes

In an array list (an array plus a length), inserting shifts the later elements back starting from the end, deleting shifts them forward starting from the front, and on average half of them move, so both are O(n) while reading a[i] stays O(1).

Getting an element by index is O(1), but inserting or deleting one in the middle means moving every element after it. In this lesson you write an array list in C and watch the moves: which way, starting from which end, and how many on average.

An array list: an array plus a length

A C array has a fixed size. To insert and delete, also keep "how many slots are in use":

1#define MAX 102 3typedef struct {4    int data[MAX];   // room for MAX elements5    int len;         // how many are there now6} SqList;

The elements sit in data[0] to data[len - 1]; the slots after that are free, for inserting.

datalen = 4free3791101234567
An array list: the first len slots hold the data, the rest are free for inserts (MAX drawn as 8 here)
Choose one

An array list holds 3 7 9 11, and len is 4. You add one more value at the end. Which slot does it go in?

Inserting: shift back, starting from the end

To insert 5 at index 1: move the element at index 1 and everything after it one slot back, which frees index 1, then put 5 there and add 1 to len.

data (len = 4)3791101234↑i
1for (int i = L->len; i > pos; i--)2    L->data[i] = L->data[i - 1];3L->data[pos] = x;4L->len++;

Inserting 5 at index 1: shift back starting from the last element, then fill the gap
Guess the outputA wrong guess is fine

Shifting from the front instead, what does it print?

1#include <stdio.h>2 3int main(void) {4    int a[5] = {3, 7, 9, 11};5    int len = 4, pos = 1;6    for (int i = pos; i < len; i++)   // shifting from the front7        a[i + 1] = a[i];8    a[pos] = 5;9    for (int i = 0; i <= len; i++)10        printf("%d ", a[i]);11    printf("\n");12    return 0;13}
Choose one

The array list is [2 4 6 8 10] (len = 5, not full). After inserting 5 at index 2, what does it look like, and how many elements moved?

Change it

Change only pos in the green box so 5 lands between 9 and 11 and the program prints 3 7 9 5 11.

1#include <stdio.h>2 3int main(void) {4    int a[6] = {3, 7, 9, 11};5    int len = 4, pos = , x = 5;6    for (int i = len; i > pos; i--)7        a[i] = a[i - 1];8    a[pos] = x;9    len++;10    for (int i = 0; i < len; i++)11        printf("%d ", a[i]);12    printf("\n");13    return 0;14}
Should print
3 7 9 5 11
Exercise 1

Write insert

Finish insert: put x at index pos (after checking the position and the room). Make the program print 1 2 4 6 8.

It should print
1 2 4 6 8
exercise1.c
1#include <stdio.h>2 3#define MAX 104 5typedef struct {6    int data[MAX];7    int len;8} SqList;9 10int insert(SqList *L, int pos, int x) {11    if (pos < 0 || pos > L->len || L->len == MAX) return 0;12    // shift back from the end, put x in, add 1 to len13    return 1;14}15 16int main(void) {17    SqList L = {{2, 4, 8}, 3};18    insert(&L, 2, 6);19    insert(&L, 0, 1);20    for (int i = 0; i < L.len; i++)21        printf("%d ", L.data[i]);22    printf("\n");23    return 0;24}
Output
Press Run or Ctrl+Enter

Deleting: shift forward, starting from the front

Deleting the element at index pos is the reverse: every element after it moves one slot forward and covers it, then len goes down by 1. This time shift from the front.

data (len = 5)35791101234↑i
1for (int i = pos; i < L->len - 1; i++)2    L->data[i] = L->data[i + 1];3L->len--;

Deleting the 5 at index 1: the ones after it move forward, starting from the front, then len goes down by 1
main.c
1#include <stdio.h>2 3#define MAX 104 5typedef struct {6    int data[MAX];7    int len;8} SqList;9 10void show(SqList *L) {11    for (int i = 0; i < L->len; i++)12        printf("%d ", L->data[i]);13    printf("(len = %d)\n", L->len);14}15 16int insert(SqList *L, int pos, int x) {17    if (pos < 0 || pos > L->len || L->len == MAX) return 0;18    for (int i = L->len; i > pos; i--)19        L->data[i] = L->data[i - 1];20    L->data[pos] = x;21    L->len++;22    return 1;23}24 25int delete_at(SqList *L, int pos) {26    if (pos < 0 || pos >= L->len) return 0;27    for (int i = pos; i < L->len - 1; i++)28        L->data[i] = L->data[i + 1];29    L->len--;30    return 1;31}32 33int main(void) {34    SqList L = {{3, 7, 9, 11}, 4};35    insert(&L, 1, 5);36    show(&L);37    delete_at(&L, 3);38    show(&L);39    return 0;40}
Output
3 5 7 9 11 (len = 5)
3 5 7 11 (len = 4)

Note the checks at the start of both functions: a bad position, or no room left, returns 0. C won't check for you, so an array list needs these lines.

Guess the outputA wrong guess is fine

What if a delete shifted from the back to the front? What would this print?

1#include <stdio.h>2 3int main(void) {4    int a[5] = {3, 5, 7, 9, 11};5    int len = 5, pos = 1;6    for (int i = len - 2; i >= pos; i--)7        a[i] = a[i + 1];8    len--;9    for (int i = 0; i < len; i++)10        printf("%d ", a[i]);11    printf("\n");12    return 0;13}
Choose one

The array list is [5 8 1 6 3] (len = 5). After deleting the element at index 1, what does it look like, and how many elements moved?

Choose one

For an array list with len = 5, which values of pos does insert accept? (Look at the check on its first line.)

Exercise 2

Write delete

Finish delete_at: remove the element at index pos and shift the rest forward.

It should print
1 2 3 4
exercise2.c
1#include <stdio.h>2 3#define MAX 104 5typedef struct {6    int data[MAX];7    int len;8} SqList;9 10int delete_at(SqList *L, int pos) {11    if (pos < 0 || pos >= L->len) return 0;12    // shift forward from the front, take 1 off len13    return 1;14}15 16int main(void) {17    SqList L = {{1, 2, 9, 3, 4}, 5};18    delete_at(&L, 2);19    for (int i = 0; i < L.len; i++)20        printf("%d ", L.data[i]);21    printf("\n");22    return 0;23}
Output
Press Run or Ctrl+Enter

How many move on average

In an array list of length n:

OperationBest (at the end)Worst (at the front)Average
Insert0 movesn movesn/2 moves
Delete0 movesn − 1 moves(n − 1)/2 moves

So inserting and deleting in an array list are O(n), while getting by position is O(1).

Often asked: textbooks count positions from 1, so "insert at position i" is index i − 1 of the C array. Average moves: n/2 to insert, (n − 1)/2 to delete.

Choose one

In an array list of length n, how many elements move when you insert at position i (counting from 1, as textbooks do)?

Removing every x in one pass

To remove every element equal to x, calling delete_at for each one shifts every time: O(n²) at worst. Better: one pass, with k keeping "the slot the next kept element goes to":

a3134353201234567↑i↑k
1int k = 0;2for (int i = 0; i < len; i++)3    if (a[i] != x)4        a[k++] = a[i];5len = k;

Removing every 3: i looks at each one, anything that isn't 3 goes to slot k and k moves on; i is never behind k, so nothing not yet looked at is overwritten
main.c
1#include <stdio.h>2 3int main(void) {4    int a[8] = {3, 1, 3, 4, 3, 5, 3, 2};5    int len = 8, x = 3;6    int k = 0;                  // how many are kept, and where the next one goes7    for (int i = 0; i < len; i++)8        if (a[i] != x)9            a[k++] = a[i];      // not x: keep it, moved forward10    len = k;11    for (int i = 0; i < len; i++)12        printf("%d ", a[i]);13    printf("\n");14    return 0;15}
Output
1 4 5 2 

One pass, each element moved at most once: O(n) time, O(1) extra space. A classic exam and interview question.

Guess the outputA wrong guess is fine

After the removal, print all 8 slots (not just the first len). What do you see?

1#include <stdio.h>2 3int main(void) {4    int a[8] = {3, 1, 3, 4, 3, 5, 3, 2};5    int len = 8, x = 3, k = 0;6    for (int i = 0; i < len; i++)7        if (a[i] != x)8            a[k++] = a[i];9    len = k;10    for (int i = 0; i < 8; i++)11        printf("%d ", a[i]);12    printf("\n");13    return 0;14}
Choose one

Remove every 2 from [2 7 2 2 5 7] (the same single pass, keeping values at a[k]). Afterwards, what is k, and what are the first k slots?

Exercise 3

Remove every negative number

In one pass, remove every number below 0 (moving the kept ones forward), then print the array.

It should print
4 5 8 3
exercise3.c
1#include <stdio.h>2 3int main(void) {4    int a[7] = {4, -1, 5, -9, -2, 8, 3};5    int len = 7;6    int k = 0;7    // one pass: keep the ones that aren't below 0, at a[k]8    len = k;9    for (int i = 0; i < len; i++)10        printf("%d ", a[i]);11    printf("\n");12    return 0;13}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Array list: insert shifts back from the end, delete shifts forward from the front

  • Get O(1); insert and delete move half on average, O(n)
  • Check the position and the room first: C won't
  • Remove every x: one pass, kept ones move forward, O(n)
1for (i = len; i > pos; i--) a[i] = a[i - 1];   // insert2for (i = pos; i < len - 1; i++) a[i] = a[i + 1]; // delete3for (i = 0; i < len; i++) if (a[i] != x) a[k++] = a[i];