-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.c
More file actions
44 lines (36 loc) · 867 Bytes
/
bubble_sort.c
File metadata and controls
44 lines (36 loc) · 867 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
#include <stdio.h>
/*
* Pass sequentially over a list, compare each value to the one immediately after it.
* If greater, the items switch. Boolean value keeps track of any changes, if there were none,
* the algorithm exits.
*/
void bubbleSort (int *array, int size)
{
int changePresent = 1;
int i, temp;
while (changePresent)
{
changePresent = 0;
for (i = 1; i < size; i ++) {
if (array[i] < array[i - 1])
{
temp = array[i];
array[i] = array[i - 1];
array[i - 1] = temp;
changePresent = 1;
}
}
}
}
int main(void)
{
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
bubbleSort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}