Programs & Examples
Arrays · Study material
Transpose of a matrix
Swap rows and columns: element m[r][c] goes to t[c][r]. A 2 × 3 matrix becomes 3 × 2.
#include <stdio.h>
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
int t[3][2];
for (int r = 0; r < 2; r++)
for (int c = 0; c < 3; c++)
t[c][r] = m[r][c];
for (int r = 0; r < 3; r++)
printf("%d %d\n", t[r][0], t[r][1]);
return 0;
}
1 4 2 5 3 6
Insertion sort
Take each element and slide it left into its place among the already-sorted ones. Fast for small or nearly-sorted arrays, and stable.
#include <stdio.h>
void insertion_sort(int *a, int n) {
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) { /* shift bigger values one place right */
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
int main(void) {
int a[] = {29, 10, 14, 37, 13};
insertion_sort(a, 5);
for (int i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
10 13 14 29 37
Sorting with qsort() and a comparator
The standard library sorts any array; you supply a function that compares two elements. Returning (a > b) - (a < b) avoids the overflow that a - b causes for large values.
#include <stdio.h>
#include <stdlib.h>
static int by_value(const void *x, const void *y) {
int a = *(const int *) x, b = *(const int *) y;
return (a > b) - (a < b); /* never "a - b": that can overflow */
}
int main(void) {
int a[] = {42, -7, 19, 0, 3};
qsort(a, 5, sizeof a[0], by_value);
for (int i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
-7 0 3 19 42
A 2D array on the heap with one malloc()
A pointer to a row (int (*m)[cols]) lets one malloc() hold the whole matrix while you still write m[r][c]. One block is faster and easier to free than an array of row pointers.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int rows = 3, cols = 4;
int (*m)[cols] = malloc(rows * sizeof *m); /* one block, used as m[r][c] */
if (m == NULL)
return 1;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
m[r][c] = r * cols + c;
printf("m[2][3] = %d, block = %zu bytes\n", m[2][3], rows * sizeof *m);
free(m); /* one malloc, one free */
return 0;
}
m[2][3] = 11, block = 48 bytes