Bubble sort implementation in C

     Sorting is the process of arranging elements in order. Bubble sort is one of the basic sorting methods which compares adjacent elements. It swaps if the elements are not sorted. Otherwise, it keeps the array elements and moves to the next adjacent elements.

👉Implementation:

  • This implementation starts with including the built-in header file. Next, a function to swap the elements is defined.
  • It uses a temporary variable to exchange the values.
  • The function ‘bubble_Sort()’ gets the input as array and its size.
  • It checks the adjacent elements value. If these are sorted already, it keeps the values.
  • Else, it swaps the values.
  • ‘main()’ function gets the array size and elements from the user.
  • It calls the ‘bubble_Sort()’ function and gets the output.
  • Finally,it prints the sorted array.

##C Code:

#include <stdio.h>

// Function to swap two elements

void b_swap(int *x, int *y) {

    int temp = *x;

    *x = *y;

    *y = temp;

}

// Here is the Bubble Sort function

void bubble_Sort(int a[], int n) {

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

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

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

                b_swap(&a[j], &a[j + 1]);

            }

        }

    }

}

// The Main function is given below

int main() {

    int a[10];

    int i,n;

    printf("Enter the number of elements");

    scanf("%d",&n);

    printf("Enter the elements");

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

    {

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

    }

    bubble_Sort(a, n);

    printf("The Sorted array is: ");

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

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

    }

    return 0;

}

⎙Output:

Enter the number of elements 6

Enter the elements 45 32 78 9 56 90

The Sorted array is: 9 32 45 56 78 90

Yes. The bubble sort implementation in C was completed. Hope, this code is useful to you. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Symmetric Encryption in java

File handling in C++