Skip to content

Abhishek-Singh296/Bubble-Sort

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

Bubble-Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

Working

Suppose we are trying to sort the elements in ascending order.

1. First Iteration (Compare and Swap)

  • Starting from the first index, compare the first and the second elements.
  • If the first element is greater than the second element, they are swapped.
  • Now, compare the second and the third elements. Swap them if they are not in order.
  • The above process goes on until the last element.

Bubble-sort-0

2. Remaining Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the unsorted elements is placed at the end.

Bubble-sort-1

In each iteration, the comparison takes place up to the last unsorted element.

Bubble-sort-2

The array is sorted when all the unsorted elements are placed at their correct positions.

Bubble-sort-3


Code

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

#define MAX_SIZE 5

void bubble_sort(int[]);

int main() {
    int arr_sort[MAX_SIZE], i;

    printf("Simple Bubble Sort Example - Array and Functions\n");
    printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
    for (i = 0; i < MAX_SIZE; i++)
        scanf("%d", &arr_sort[i]);

    printf("\nYour Data   :");
    for (i = 0; i < MAX_SIZE; i++) {
        printf("\t%d", arr_sort[i]);
    }

    bubble_sort(arr_sort);
    getch();
}

void bubble_sort(int fn_arr[]) {
    int i, j, a, t;

    for (i = 1; i < MAX_SIZE; i++) {
        for (j = 0; j < MAX_SIZE - 1; j++) {
            if (fn_arr[j] > fn_arr[j + 1]) {
                //Swapping Values 
                t = fn_arr[j];
                fn_arr[j] = fn_arr[j + 1];
                fn_arr[j + 1] = t;
            }
        }

        printf("\nIteration %d : ", i);
        for (a = 0; a < MAX_SIZE; a++) {
            printf("\t%d", fn_arr[a]);
        }
    }

    printf("\n\nSorted Data :");
    for (i = 0; i < MAX_SIZE; i++) {
        printf("\t%d", fn_arr[i]);
    }
}

Output

Screenshot 2023-04-24 023120

Releases

No releases published

Packages

No packages published

Languages