Arrays

Created by Miroslav Biňas / mirek

DRY

Don't Repeat Yourself

KISS

Keep It Simple, Stupid

Arrays

Array Overview

Array Overview

Array Overview

Array Overview

Array Overview

Array Overview

for

for(int idx = 0; idx < 10; idx++){
    // some magic
}
                

while

int idx = 0;
while(idx < 10){
    // some magic
    idx++;
}
                

Fencepost problem

| 1m | 1m | 1m | 1m | 1m |

Off-by-one Error

(Fencepost error)

Segmentation Fault

Common
Operations
with Arrays

Searching

 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?

Linear Search

Size of Array

// total amount of memory in bytes
sizeof(arr_name);
// number of elements
sizeof(arr_name) / sizeof(arr_name[idx]);

Function Parameter

// function call, array sent via address
fun(arr_name);
// declaration, add size as parameter
type fun(type arr_name[], type size);

Function Parameter

// count size first
type size = 
   sizeof(arr_name) / sizeof(arr_name[idx]);
// then send as parameter
fun(arr_name, size);

Binary Search

Algorithm
Complexity

Big O Notation

Sorting

4 1 5 9 8 2 3

1 4 5 9 8 2 3

1 4 5 8 9 2 3

1 4 5 8 2 9 3

1 4 5 8 2 3 9

1 4 5 2 8 3 9

1 4 5 2 3 8 9

1 4 2 5 3 8 9

1 4 2 3 5 8 9

1 2 4 3 5 8 9

1 2 3 4 5 8 9

Bubble Sort

stdlib.h

Quick Sort

Questions?