-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse.c
More file actions
63 lines (53 loc) · 1.79 KB
/
reverse.c
File metadata and controls
63 lines (53 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Jacobus Burger (2022)
*
* Info:
* I wondered about a fast way to reverse an array of elements
* and imagined iterating halfway across the array and then
* swapping the current element with its "mirror".
* Explanation:
* The algorithm works by iterating through half the length of
* the array, it then swaps the current element with its
* "mirror" (the current index from the length of the whole array).
* This results in swapping all the elements swapping in what
* I approximate to be O(n/2) time.
*/
#include <stdio.h>
#include <assert.h>
void reverse(int* array, int length) {
for (int i = 0; i < length / 2 + 1; i++) {
int temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
void print_array(int* array, int length) {
for (int i = 0; i < length; i++)
printf("%i ", array[i]);
printf("\n");
}
char equals_array(int* A, int A_length, int* B, int B_length) {
if (A_length != B_length)
return 0;
for (int i = 0; i < A_length; i++)
if (A[i] != B[i])
return 0;
return 1;
}
int main(void) {
// create array
#define LEN 16
int a[LEN] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
// check that it works as intended
print_array(a, LEN);
reverse(a, LEN);
print_array(a, LEN);
reverse(a, LEN);
print_array(a, LEN);
// test properties
// property: identity (a == a)
assert(equals_array(a, LEN, a, LEN));
// property: idempotence (rev(rev(a)) == a)
reverse(a, LEN);
reverse(a, LEN);
assert(equals_array(a, LEN, a, LEN));
}