-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubble Sort.c
More file actions
36 lines (32 loc) · 967 Bytes
/
Bubble Sort.c
File metadata and controls
36 lines (32 loc) · 967 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
#include <stdio.h>
int main()
{
int arr[] = {5, 1, 4, 2, 8}; // sample array to sort
int n = 5; // size of the array
int i, j, temp; // variables for loops and swapping
// print the original array
printf("Original array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
// bubble sort algorithm
for (i = 0; i < n - 1; i++) // outer loop for passes
{
for (j = 0; j < n - i - 1; j++) // inner loop for comparisons
{
if (arr[j] > arr[j + 1]) // if the current element is greater than the next element
{
// swap the elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// print the sorted array
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}