File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /* Program to sort array using bubble sort */
2+
3+ #include <stdio.h>
4+ #include <stdlib.h>
5+ // function to sort array using bubble sort
6+ void bubble_sort (int a [],int size )
7+ {
8+ int round ,i ,swap = 0 ;
9+ // run loop until round is less than size
10+ for (round = 1 ;round <=size - 1 ;round ++ )
11+ {
12+ // run inner loop until i is less than size-round
13+ for (i = 0 ;i < size - round ;i ++ )
14+ {
15+ if (a [i ]>=a [i + 1 ])
16+ {
17+ // swap a[i] and a[i+1]
18+ swap = a [i ];
19+ a [i ]= a [i + 1 ];
20+ a [i + 1 ]= swap ;
21+ }
22+ }
23+ }
24+ // print the output
25+ printf ("Bubble sort: " );
26+ for (i = 0 ;i < size ;i ++ )
27+ printf ("%d " ,a [i ]);
28+ }
29+ // driver code
30+ int main ()
31+ {
32+ int * arr ,i ,n ;
33+ printf ("Enter the size: " );
34+ // taking size
35+ scanf ("%d" ,& n );
36+ // dynamically allocating array in arr
37+ arr = (int * )malloc (sizeof (int )* n );
38+ printf ("Enter %d numbers\n" ,n );
39+ for (i = 0 ;i < n ;i ++ )
40+ scanf ("%d" ,& arr [i ]);
41+ // calling bubble sort function
42+ bubble_sort (arr ,n );
43+
44+ return 0 ;
45+
46+ }
47+ /*
48+ Input: Enter the size: 10
49+ Enter 10 numbers
50+ 10 9 8 7 6 5 4 3 2 1
51+ Output:
52+ Bubble sort: 1 2 3 4 5 6 7 8 9 10
53+
54+ Time complexity: O(N^2)
55+
56+ */
You can’t perform that action at this time.
0 commit comments