• Bubble Sort

    Bubble Sort

    Introduction:

    In bubble sort method the list is divided into two virtual sub-lists called unsorted and sorted. The smallest element is bubbled from unsorted sub-list to sorted sub-list. After moving the smallest element the imaginary wall moves one element ahead.

    The bubble sort was originally written to bubble up the highest element in the list. But there is no difference whether highest/lowest element is bubbled. This method is easy to understand but time consuming. In this type, two successive elements are compared and sapping is done. Thus, step-by-step entire array elements are checked. Given a list of ‘n’ elements the bubble sort requires up to n-1 passes to sort the data.

    Algorithm of Bubble Sort:

    Bubble_sort (n, list)

    Where

    N -> Represents the number of elements in the list

    L -> Represents the list of elements

    Step 1: [Initialize]

    i = 0

    Step 2: Repeat through step 5 while ( i < n )

    Step 3 : j = 0;

    Step 4: Repeat through step 5 while ( j < n-i)

    Step 5: if (list[ j] < list [ j+1]

    • temp = list[ j]
    • list[ j+1] = list[ j]
    • list[j] = temp

    step 6: Exit

    Example – Bubble Sort on Array/List using C Language

    #include<stdio.h>#include<stdio.h>

    void bubble_sort (int array[], int  size)

    {

    int temp, i, j;

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

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

    if (array[j] < array[ j+1]    )

    {

    temp = array[j];

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

    array[ j+1] = temp;

    }

    }

    void main(void)

    {

    int values[30], i;

    printf(“\n Unsorted list is as follows\n”);

     

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

    {

    values[i] = rand( ) %100;

    printf(“%d”, values[i]);

    }

    bubble_sort (values , 10);

        printf(“\n Sorted list is as follows\n”);

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

    printf(“%d”,values[i]);

    }

    Appreciate my work :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg thisShare on YummlyShare on VKFlattr the authorBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *