By using Bubble sort to sort the numbers or arrange them in ascending order. With simple modification to print the numbers in descending order.
C Program for Bubble Sort |
||
1 | #include <stdio.h> | |
2 | int main() | |
3 | { | |
4 | int array[100], n, c, d, swap; | |
5 | printf("Enter_number_of_elements\n"); | |
6 | scanf("%d", &n); | |
7 | printf("Enter %d integers\n", n); | |
8 | for (c = 0; c < n; c++) | |
9 | scanf("%d", &array[c]); | |
10 | for (c = 0 ; c < ( n - 1 ); c++) | |
11 | { | |
12 | for (d = 0 ; d < n - c - 1; d++) | |
13 | { | |
14 | if (array[d] > array[d+1]) /* For_decreasing_order_use */ | |
15 | { | |
16 | swap = array[d]; | |
17 | array[d] = array[d+1]; | |
18 | array[d+1] = swap; | |
19 | } | |
20 | } | |
21 | } | |
22 | printf("Sorted_list_in_ascending_order:\n"); | |
23 | for ( c = 0 ; c < n ; c++ ) | |
24 | printf("%d\n", array[c]); | |
25 | return 0; | |
26 | } |
Output:
Bubble Sort Program By using Functions:
1 | #include <stdio.h> | |
2 | void bubble_sort(long [], long); | |
3 | int main() | |
4 | { | |
5 | long array[100], n, c, d, swap; | |
6 | printf("Enter_number_of_elements\n"); | |
7 | scanf("%ld", &n); | |
8 | printf("Enter %ld integers\n", n); | |
9 | for (c = 0; c < n; c++) | |
10 | scanf("%ld", &array[c]); | |
11 | bubble_sort(array, n); | |
12 | printf("Sorted_list_in_ascending_order:\n"); | |
13 | for ( c = 0 ; c < n ; c++ ) | |
14 | printf("%ld\n", array[c]); | |
15 | return 0; | |
16 | } | |
17 | void bubble_sort(long list[], long n) | |
18 | { | |
19 | long c, d, t; | |
20 | for (c = 0 ; c < ( n - 1 ); c++) | |
21 | { | |
22 | for (d = 0 ; d < n - c - 1; d++) | |
23 | { | |
24 | if (list[d] > list[d+1]) | |
25 | { | |
26 | /* Swapping */ | |
27 | t = list[d]; | |
28 | list[d] = list[d+1]; | |
29 | list[d+1] = t; | |
30 | } | |
31 | } | |
32 | } | |
33 | } |