C program to sort an array in ascending and descending order using bubble sort

Bubble sort program in C: In this tutorial, we will learn how to sort an array in ascending and descending order using bubble sort with the help of the C program? By IncludeHelp Last updated : August 03, 2023

Bubble Sort is a simple method to sort lists, in this sorting technique, we compare adjacent elements and swap if they are in the wrong order. This process repeats until no more swaps are needed.

Problem statement

In this program, we will read N number of elements in a One Dimensional Array and arrange all elements in Ascending and Descending Order using Data Structure Bubble Sort technique.

C program to sort an array in ascending and descending order using bubble sort

/*Bubble Sort - C program to sort an Array 
in Ascending and Descending Order.*/
 
#include <stdio.h>
 
#define MAX 100
 
int main()
{
    int arr[MAX],limit;
    int i,j,temp;
     
    printf("Enter total number of elements: ");
    scanf("%d",&limit);
     
    /*Read array*/
    printf("Enter array elements: \n");
    for(i=0; i<limit; i++)
    {
        printf("Enter element %3d: ",i+1);
        scanf("%d",&arr[i]);
    }
     
    /*sort elements in Ascending Order*/
    for(i=0; i<(limit-1); i++)
    {
        for(j=0; j<(limit-i-1); j++)
        {
            if(arr[j]>arr[j+1])
            {
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
    }
 
    printf("Array elements in Ascending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
     
    printf("\n");
         
    /*sort elements in Descending Order*/
    for(i=0; i<(limit-1); i++)
    {
        for(j=0; j<(limit-i-1); j++)
        {
            if(arr[j]<arr[j+1])
            {
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
    }
 
    printf("Array elements in Descending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
     
    printf("\n");
     
    return 0;
}

Output

Enter total number of elements: 10
Enter array elements:
Enter element 1: 12
Enter element 2: 34
Enter element 3: 43
Enter element 4: 32
Enter element 5: 21
Enter element 6: 1
Enter element 7: 11
Enter element 8: 2
Enter element 9: 3
Enter element10: 100
Array elements in Ascending Order:
1 2 3 11 12 21 32 34 43 100
Array elements in Descending Order:
100 43 34 32 21 12 11 3 2 1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.