Write a c program to perform bubble sort

Write a c program to perform bubble sort

Asked on January 21, 2020 in program.
int main()
{
int array[100], n, i, j, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbers:n", n);
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])
{
swap=array[j];
array[j]=array[j+1];
array[j+1]=swap;
}
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", array[i]);
return 0;
}
on January 21, 2020.
Add Comment
1 Answer(s)
  • Bubble sort in C to arrange numbers in ascending order, you can modify it for descending order and can also sort strings.
  • The bubble sort algorithm isn’t efficient as its average-case complexity is O(n2) and worst-case complexity is O(n2).
  • There are many fast sorting algorithms like Quicksort, heap-sort, and others.
  • Sorting simplifies problem-solving in computer programming.

Bubble sort program in C

/* Bubble sort code */
#include <stdio.h>

int main()
{
int array[100], n, c, d, swap;

printf(“Enter number of elements\n”);
scanf(“%d”, &n);

printf(“Enter %d integers\n”, n);

for (c = 0; c < n; c++)
scanf(“%d”, &array[c]);

for (c = 0 ; c < n – 1; c++)
{
for (d = 0 ; d < n – c – 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

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

for (c = 0; c < n; c++)
printf(“%d\n”, array[c]);

return 0;
}

Let’s understand with the below example:

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

Example:
First Pass:
5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Answered on January 21, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.