-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.c
More file actions
70 lines (55 loc) · 1.29 KB
/
bubble_sort.c
File metadata and controls
70 lines (55 loc) · 1.29 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
64
65
66
67
68
69
70
#include <stdio.h>
/**
* Swaps two integer values.
*/
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
/**
* Main bubble sort algorithm. Takes in an array and sorts it in place.
*/
void bubbleSort(int *arr, int n) {
int i, j, swapped;
// Outer loop
for (i = 0; i < n; i++) {
swapped = 0;
// Inner loop - "bubble up" the highest element
for (j = 0; j < n - i - 1; j++) {
// Check if we need to swap
if (arr[j] > arr[j+1]) {
// Swap
swap(&arr[j], &arr[j+1]);
swapped = 1;
}
}
// If there were no swaps on the last inner loop, then we are done
if (swapped == 0) {
break;
}
}
}
/**
* Prints out an array to std out.
*/
void printArray(int *arr, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i < n - 1) {
printf(", ");
}
}
printf("\n\n");
}
int main() {
int input_array[] = {9, 8, 2, 4, 10, 5, 7, 6, 3, 1, 7};
int size = 10;
printf("Before:\n");
printArray(input_array, size);
bubbleSort(input_array, size);
printf("After:\n");
printArray(input_array, size);
return 0;
}