-
Notifications
You must be signed in to change notification settings - Fork 6
/
bubble_sort.c
75 lines (64 loc) · 1.96 KB
/
bubble_sort.c
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
#include <stdio.h>
//Following function will sort the array in Increasing (ascending) order
void bubble_sort(int arr[], int n)
{
int i, j, tmp;
for(i = 0; i < n-1; i++)
{
// Last i elements are already in place, so the inner loops will run until it reaches the last i elements
for(j = 0; j < n-i-1; j++)
{
if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<'
{
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
//Following is a slightly modified bubble sort function, which tracks the list with a flag to check if it is already sorted
void modified_bubble_sort(int arr[], int n)
{
int i, j, tmp;
for(i = 0; i < n-1; i++)
{
int flag = 0; //Taking a flag variable
// Last i elements are already in place, so the inner loops will run until it reaches the last i elements
for(j = 0; j < n-i-1; j++)
{
if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<'
{
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
flag = 1; //Setting the flag, if swapping occurs
}
}
if(!flag) //If not swapped, that means the list has already sorted
{
break;
}
}
}
void print_list(int arr[], int num_of_element)
{
int i;
for(i = 0; i < num_of_element; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int arr[] = {43, 1, 24, 56, 30, 5};
int num_of_element = sizeof(arr)/sizeof(int);
printf("Initial List:\n");
print_list(arr, num_of_element);
bubble_sort(arr, num_of_element);
//modified_bubble_sort(arr, num_of_element);
printf("Sorted list in ascending order: \n");
print_list(arr, num_of_element);
return 0;
}