forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble_sort.c
75 lines (61 loc) · 1.58 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>
#define MAX 100
/*Bubble sort is an algorithm that compares the adjacent elements and swaps
their positions if they are not in the intended order.
The order can be ascending or descending.
*/
//prototyping the bubble sort function
void bubble_sort(int a[], int len); //utility function to sort
void print_array(int a[], int n); //utility function for printiong an array
//initializing main function
int main(int argc, char const *argv[])
{
//initial array to store elements for sorting.
int A[MAX];
//size element to define the size of the array.
int size, i, j;
printf("enter the size of array you want:");
scanf("%d", &size);
//taking the elements in the array
for (i = 0; i < size; i++)
{
/* take the elements from user */
printf("\n");
printf("enter the element of the array:");
scanf("%d", &A[i]);
}
printf("\n");
printf("the initial unsorted array:");
print_array(A, size);
bubble_sort(A, size);
printf("\n\n");
printf("The final sorted array:");
print_array(A, size);
return 0;
}
void bubble_sort(int a[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
j = i;
for (j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
/* code */
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
void print_array(int a[], int n)
{
for (int i = 0; i < n; i++)
{
/* code */
printf(" %d ", a[i]);
}
}