-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble_sort.c
57 lines (52 loc) · 1.07 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
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int *, int);
void display(int *, int);
void input(int *, int);
int main()
{
int *arr;
int n;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
arr = (int *)malloc(sizeof(int) * n);
printf("Enter %d elements: ", n);
input(arr, n);
bubble_sort(arr, n);
printf("Elements after sorting: ");
display(arr, n);
return 0;
}
void bubble_sort(int *arr, int n)
{
int i, j, swapped, temp;
for (i = n - 1; i >= 0; i--)
{
swapped = 0;
for (j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped++;
}
}
if (swapped == 0)
break;
}
}
void input(int *arr, int n)
{
int i;
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
}
void display(int *arr, int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}