C Program to Sort a random array of n integers using bubble sort algorithm | DS - IProgramX

Q. Sort a random array of n integers (accept the value of n from user) in ascending order by using bubble sort algorithm


Program

#include <stdio.h>
#define MAXSIZE 10

void main()
{
    int array[MAXSIZE];
    int i, j, num, temp;

    printf("Enter the value of num \n");
    scanf("%d", &num);
    printf("Enter the elements one by one \n");
    for (i = 0; i < num; i++)
    {
        scanf("%d", &array[i]);
    }
    printf("Input array is \n");
    for (i = 0; i < num; i++)
    {
        printf("%d\n", array[i]);
    }
    for (i = 0; i < num; i++)
    {
        for (j = 0; j < (num - i - 1); j++)
        {
            if (array[j] > array[j + 1])
            {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    printf("Sorted array is...\n");
    for (i = 0; i < num; i++)
    {
        printf("%d\n", array[i]);
    }
}

Output: 

Enter the value of num
4
Enter the elements one by one
3
5
3
8
Input array is
3
5
3
8
Sorted array is...
3
3
5
8

Post a Comment

0 Comments