20_10

Write a C program to sort an array using Bubble sort.

 Source code:

/*Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because smaller elements bubble toward the top of the list. Consider an array of size 10. It will be filled it by reading 10 integers. The final output will be sorted output in Ascending Order. */


#include <stdio.h>

int main()

{

  int array[10], n=10, i, j, swap;


 /* Read array elements */

printf("Enter the array: ");

  for (i = 0; i < n; i++)

    scanf("%d", &array[i]);

for (i = 0 ; i < ( n - 1 ); i++)

  {

    for (j = 0 ; j < n - i - 1; j++)

    {

      if (array[j] > array[j+1]) /* For decreasing order use < */

      {

        swap       = array[j];

        array[j]   = array[j+1];

        array[j+1] = swap;

      }

    }

  }

printf("Sorted list in ascending order:\n");


  for ( i = 0 ; i < n ; i++ )

      printf("%d\n", array[i]);

  return 0;

}

Output:
C program to sort an array using Bubble sort


No comments:

Post a Comment

Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...