Bubble sort

                               Bubble Sort




💧💧💧💧💧

The working procedure of bubble sort is very simple.Bubble sort works on the repeatedly swapping of adjacent elemnts until they are not in the intended order.This is called bubble sort because this works as bubble in water serially make its intended order.The average and worst case complexity of bubble sort is O(n^2),Where n is the number of the items

Algorithm

begin BubbleSort(arr)

for all array elements

if arr[i]>arr[i+1]

swap(arr[i],arr[i+1])

end if 

end for 

return arr

end BubbleSort

Working Procedure:

let take unsorted array elements:  13 32 26 35 10

first pass:

                 13 32 26 35 10

                 13 26 32 35 10

                  13 26 32 10 35

here we have to compare from 1st element 13 .

here 13<32

so this is already sorted

next we have to compare 

26<32

that makes

                           13 26 32 35 10

next  32<35 and 35>10

that makes

                          13 26 32 10 35

Second pass:

                                     13 26 32 10 35

                                      13 26 32 10 35

                                       13 26 32 10 35

                                        13 26 10 32 35

Third pass:

                                           13 26 10 32 35

                                            13 26 10 32 35 

                                             13 10 26 32 35 

                                              13 10 26 32 35 

forth pass:

                                              10 13 26 32 35

IMPLEMENTATION:

#include <stdio.h>


int main(){


    int arr[50], n, i, j,swap;


    printf("Please Enter the Number of Elements you want in the array: ");


    scanf("%d", &n);


    printf("Please Enter the Value of Elements: ");


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


        scanf("%d", &arr[i]);


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


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


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


                swap = arr[j];


                arr[j] = arr[j + 1];


                arr[j+ 1] = swap;


            }


        }


    }


    printf("Array after implementing bubble sort: ");


    for(i = 0; i < n; i++){


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


    }


    return 0;


}

Output:

Please Enter the Number of Elements you want in the array: 5
Please Enter the Value of Elements: 13
32
26
35
10
Array after implementing bubble sort: 10  13  26  32  35
Process returned 0 (0x0)   execution time : 43.266 s
Press any key to continue.

Post a Comment

0 Comments