-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.c
More file actions
51 lines (42 loc) · 857 Bytes
/
bubble_sort.c
File metadata and controls
51 lines (42 loc) · 857 Bytes
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void bubble_sort(int* array, int len) {
int last = len - 1, i, j, bigger;
for (i = 0; i < len; i++) {
for (j = 0; j < last; j++) {
if (array[j] > array[j+1]) {
bigger = array[j];
array[j] = array[j+1];
array[j+1] = bigger;
}
}
last--;
}
}
void print_array(int* array, int len) {
int i;
printf("[");
for (i = 0; i < len; i++) {
if (i == len-1) {
printf("%d", array[i]);
} else {
printf("%d, ", array[i]);
}
}
printf("]\n");
}
int main(int argc, const char *argv[])
{
int len;
int array[] = { 4, 5, 3, 2, 1 };
int *sorted;
len = sizeof(array) / sizeof(array[0]);
sorted = malloc(sizeof(array));
memcpy(sorted, array, sizeof(array));
bubble_sort(sorted, len);
print_array(array, len);
print_array(sorted, len);
free(sorted);
return 0;
}