×

Bubble sort in C

Bubble sort in C

Bubble sort is defined as the algorithm that is used for the sorting mechanism. It follows the technique of replacing the first index with the more minor value present within the array and then keeps it repeating until it is sorted in the correct order.

Bubble sort is the simple way of performing the sorting technique. The value of the array has to be assigned to the array first before starting the sorting.

Data sorting is considered to be an essential concept. During the times when the data needs to be arranged in a particular order or in an organized way, sorting techniques are used. Bubble sort is considered the most straightforward sorting technique among the ones present in the C standard as it is very easy to implement and understand.

It follows the approach of comparing the current element with the preceding one and then swaps it accordingly if required, such as if it is less or more significant. This gives accurate results no matter what. Every time an element is passed into an array, it will be compared with all the elements present within the array, and then it decides a final place to that inserted element and is called a pass.

Bubble sort gets the name as it filters out the elements of the top of the array, similar to the bubbles on the water. Although this algorithm is the slowest, it runs with O’s time complexity (n^2).

A bubble sort might be optimized by using the variable called to flag that exists the loop once, and then the swapping can be initiated. The best complexity of the bubble sort can be O(n).

Bubble sort algorithm:

  1. Starting from the index zero in an array, compare the element with the preceding one (a[0] and a[1] considering the name of the array as a) compare both the elements and swap if a[1] > a[2]. Repeat this process until the end of the array. After doing so, the most significant element will be placed as the end of the array. The whole thing is considered as a pass. The array elements will be processed in the first pass in the first pass [0, n - 1].
  2. Repeat the previous step but instead consider the elements from [0, n - 2] as the last one, that is, a[n - 1] is present at its correct position. After this particular step, the largest of the two elements will be compared and will be swapped.
  3. Repeat the same steps for n - 1 number of times.

E.g.:

 #include <stdio.h>
 int main()
 {
 int total_count, counter, counter1, swap_var;
 int array[20];
 printf("How many numbers do you want to input?\n");
 scanf("%d", &total_count);
 printf("Please enter %d integers that have to be sorted\n", total_count);
 for (counter = 0; counter < total_count; counter++)
 scanf("%d", &array[counter]);
 for (counter = 0 ; counter < total_count - 1; counter++)
 {
 for (counter1 = 0 ; counter1 < total_count - counter - 1; counter1++)
 {
 if (array[counter1] > array[counter1+1]) /* For decreasing order use < */
 {
 swap_var       = array[counter1];
 array[counter1]   = array[counter1+1];
 array[counter1+1] = swap_var;
 }
 }
 }
 printf("Below is the list of elements sorted in ascending order:\n");
 for (counter = 0; counter < total_count; counter++)
 printf("%d\n", array[counter]);
 return 0;
 } 

Output:

 How many numbers do you want to input?
 4
 Please enter 4 integers that have to be sorted
 4 2 5 1
 Below is the list of elements sorted in ascending order:
 1
 2
 4
 5 

Once the above program is compiled and run, it will further ask the programmer or the developer for the number of elements that they want to sort.

Once it is provided, the program will ask the user to provide values equivalent to their provided count. The values will be stored in the array and processed further using nested for loop together with decision-making using “if” to sort the array.

The first smallest value found in the array has been moved to the array’s first index, and then the search begins again to find the other smallest number.

Once the following smallest number is found, it replaces the value in the second index, and the process keeps on repeating until the array consists of a sorted list of values.

Complexities:

  • Worst case time complexity: O(n^2). If we want to sort, the array is ascending order, and the given array is in descending series.
  • Best case time complexity: O(n). if the array is already sorted in the beginning and there is no necessity of sorting.
  • Average case time complexity: O(n^2).  This occurs when the element of the array occurs in the chaotic order.

Space complexity:

  • Space complexity is always O(1) as an extra variable is used for  swapping
  • In an optimized bubble sort algorithm, an extra two of the variables will be used. Hence the space complexity will be O(2).

Applications:

  • Bubble sort can be used if the complexity does not matter
  • If the array is short and readable.

Related Topics

Sum of digits in C++

Sum of digits in C++ There are various ways to find the sum of the digits of a number in C++. We can use containers like arrays or other simple cases...

4 minutes read.

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within...

3 minutes read.

Static in C

Static is a keyword that is used in the C programming language. It can be used both as variables and as functions. In other words, it can be declared both...

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

Prime Number Program in C using for Loop

In this article, we will know about the procedure of checking whether a natural number inputted by the user is a prime number or non-prime number. Definition of the prime number A...

3 minutes read.

Diffie-Hellman Algorithm in C

Background: A method of public-key encryption known as elliptic curve cryptography (ECC) is based on the algebraic structure of elliptic curves over finite fields. To ensure equal security, ECC encryption requires fewer...

4 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

C program to find factorial of a number using Recursion

What does the term "Factorial of a Number" mean? In mathematics, factorial is the product of all positive integers that are less than or equal to a certain positive integer, and...

2 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Reverse a Stack using Recursion in C

In this tutorial we will learn how recursion will be used in this case to reverse a stack. For loops, while loops, do-while loops, and similar constructions are not permitted....

5 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

Ceil function in C

Introduction In the C Programming Language, the ceil function is a library function which is used to obtain the ceil value, i.e., it returns the smallest integer that is greater than...

4 minutes read.

Structure in C

Why Structure came into the picture? In the actual world, we deal with entities that are collections of objects rather than tiny bits of data like integers, characters, floats, etc. So,...

4 minutes read.

Find out Power without using POW function in C

Introduction: In this discussion, we will discuss how we find out power without using the POW function in C. In this article, you'll understand how to compute integer powers in...

3 minutes read.

Expressions in C

Expressions in C: In the C programming language, an expression defines a formula in which the operands are linked to each other by using operators to compute the value. The operand...

4 minutes read.