Bubble Sort

 Bubble Sort

In Bubble sort, Each element of the array is compared with its adjacent element. The algorithm processes the list in passes. A list with n elements requires n-1 passes for sorting. Consider an array A of n elements whose elements are to be sorted by using Bubble sort. The algorithm processes like following.

  1. In Pass 1, A[0] is compared with A[1], A[1] is compared with A[2], A[2] is compared with A[3] and so on. At the end of pass 1, the largest element of the list is placed at the highest index of the list.

  2. In Pass 2, A[0] is compared with A[1], A[1] is compared with A[2] and so on. At the end of Pass 2 the second largest element of the list is placed at the second highest index of the list.

  3. In pass n-1, A[0] is compared with A[1], A[1] is compared with A[2] and so on. At the end of this passes. The smallest element of the list is placed at the first index of the list.

Algorithm:

  • Step 1: Repeat Step 2 For i = 0 to N-1

  • Step 2: Repeat For J = i + 1 to N - I

  • Step 3: IF A[J] > A[i]
    SWAP A[J] and A[i]
    [END OF INNER LOOP]
    [END OF OUTER LOOP

  • Step 4: EXIT

 

Example:-

C Program

#include<stdio.h>  

void main ()  

{  

    int i, j,temp;   

    int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};   

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

    {  

        for(j = i+1; j<10; j++)  

        {  

            if(a[j] > a[i])  

            {  

                temp = a[i];  

                a[i] = a[j];  

                a[j] = temp;   

            }   

        }   

    }   

    printf("Printing Sorted Element List ...\n");  

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

    {  

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

    }  

}  

 

C++ Program


#include<iostream>  

using namespace std;  

int main ()  

{  

    int i, j,temp;   

    int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};   

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

    {  

        for(j = i+1; j<10; j++)  

        {  

            if(a[j] < a[i])  

            {  

                temp = a[i];  

                a[i] = a[j];  

                a[j] = temp;   

            }   

        }   

    }   

    cout <<"Printing Sorted Element List ...\n";  

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

    {  

        cout <<a[i]<<"\n";  

    }  

    return 0;  

}  


Output:

Printing Sorted Element List . . . 

7

9

10

12

23

34

34

44

78 

101



Comments

Popular posts from this blog

Huffman coding || Huffman coding with example || Huffman coding method || Huffman coding in c/c++ ||Huffman coding programe in c/c++/data structure /java || what is Huffman coding || Huffman complete,

Ada important question bank

Unix assignment question

Graphs in data structure, it's algorithm

Java question bank

M-way Trees

Data structure question bank

B Tree

Radix Sort

csa unit 01 part 01 basic of computers notes pdf