Loading, please wait...

Bubble Sort

In bubble sort each element in compared with its adjacent element. If the first element is larger than the second one then the position of elements are un-changed. Otherwise it not changed.

Then the next is compared with its adjacent elements is compared with its adjacent elements and the same process is repeated for all element in array.

During the pass second largest element occupies the second last position. During the second pass the same process is repeated leaving the large element. During pass the largest element occupies the n-1 position .The same process is repeated until no more elements are left for comparison.

 

Algorithm:

  1. Initialize BubbleSort(list) Set I = 0
  2. Repeat steps 3 to 5 until I < N
  3. Set j = 0
  4. Repeat step 5 until j<N-i-1
  5. If A[j] > A[j+1]
  6. Set temp = A[j]
  7. Set A[j] = a[j+1]
  8. Set a[j+1] = temp
  9. end if
  10. Exit BubbleSort

 

Example:

Initially take unsorted array contains element:

5 3 8 4 6

Step1: Compare the first and second element and swap

5 3 8 4 6

Step2: Compare the second and third element and swapping will perform here.

3 5 8 4 6

Step3: Compare the third and fourth element and swap

3 5 8 4 6

Step4: Compare the fourth and fifth element and swap

3 5 4 8 6

Step5: Repeat Step 1to 5 until no more swaps required. And the final sorted array will be as.

3 5 4 6 8

 

Listing: Following program is showing the implementation of Bubble sort.

/* 
* C program to sort N numbers in ascending order using Bubble sort 
* and print both the given and the sorted array 
*/ 
#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]); 
    } 
    /*   Bubble sorting begins */ 
    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]); 
    } 
} 
advertisements 
Output: 

    Enter the value of num 
    6 
    Enter the elements one by one 
    23 
    45 
    67 
    89 
    12 
    34 
    Input array is 
    23 
    45 
    67 
    89 
    12 
    34 
    Sorted array is... 
    12 
    23 
    34 
    45 
    67 
    89