-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.c
More file actions
90 lines (75 loc) · 1.63 KB
/
bubble_sort.c
File metadata and controls
90 lines (75 loc) · 1.63 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* Bubble Sort
* Repeatedly swap elements to bubble large elements to the end
* The further sorted it becomes it reduces how many pairs that need
* to be compared
*
* Worst-case time complexity of O(n2)
*/
#include <stdbool.h>
#include <stdio.h>
void bubble_sort(int arr[], int N);
void print_array(int arr[], int len);
void swap(int arr[], int a, int b);
int main(void)
{
// array of random integers
int integers[] = {
6,
48,
98,
53,
94,
13,
41,
52,
18,
67
};
// array size
int len = (sizeof(integers) / sizeof(integers[0]));
printf("Unsorted Array: \n");
print_array(integers, len);
bubble_sort(integers, len);
printf("Sorted Array: \n");
print_array(integers, len);
return 0;
}
void bubble_sort(int arr[], int N)
{
// loop from start of array to second last index
for (int i = 0; i < N - 1; i++)
{
bool swapped = false;
// loop from start of array to (array length - current index - 1)
for (int j = 0; j < N - i - 1; j++)
{
if (arr[j] > arr[j+1])
{
// swap
swap(arr, j, j+1);
swapped = true;
}
}
if (!swapped)
{
break;
}
}
}
void print_array(int arr[], int len)
{
for (int i = 0; i < len; i++)
{
printf("%i ", arr[i]);
}
printf("\n");
}
void swap(int arr[], int a, int b)
{
// given two indexes as ints swap,
// their position in array
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}