# Bubble Sort in C

0 like 0 dislike
4.5k views
Bubble Sort in C

0 like 0 dislike
by Goeduhub's Expert (7.6k points)
edited

## Bubble Sort in C

Bubble sort : Bubble sort  is a sorting algorithm which  is also called  comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Example

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

Second Pass :
1 , 4  , 2 ,15 ,18  =>  1 , 4 , 2 ,15 ,18
1 , 4 , 2 , 15 ,18  =>  1 , 2 , 4 ,15 ,18   #Swap since 4 > 2
1 ,2 , 4 , 15 , 18  =>  1 , 2  ,4 ,15 ,18
1 , 2 , 4 ,15  ,18  =>  1 , 2 , 4 ,15 ,18

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 ,15 ,18  =>  1 ,2 ,4 ,15, 18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15 ,18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15, 18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15 ,18

Algorithm

if (arr[j] > arr[j+1])

swap(&arr[j], &arr[j+1]);

Program

#include <stdio.h>

#include <stdlib.h>

#include<conio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

void bubbleSort(int arr[], int n)

int i, j;

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

// Last i elements are already in place

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

if (arr[j] > arr[j+1])

swap(&arr[j], &arr[j+1]);

}

void printArray(int arr[], int size)

int i;

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

printf("%d ", arr[i]);

printf("\n");

int main()

int arr[] = {64, 34, 205, 112, 2, 1, 9};

int n = sizeof(arr)/sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array: \n");

printArray(arr, n);

return 0;

Output

## For more Manipal University Jaipur B.Tech CSE-III Sem Data Structure Lab Experiments Click here

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.