×

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

2f in C language

Float data type in c: Double-precision floating-point numbers with up to 17 significant digits are stored in the FLOAT data type. FLOAT is equivalent to C's double data type and IEEE...

3 minutes read.

Pre-increment and Post-increment in C

The rich set of operators is supported by the c language. In c there are several operators used. The mathematical operations in the programming language are done with the operators...

4 minutes read.

Modulus on Negative Numbers in C

In this tutorial, we will explore some examples of modulus on negative number. What is Modulus of Negative number? By omitting the minus sign, one can determine the modulus of a negative...

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.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

C Token

C Token and Keyword The C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in the C program is...

2 minutes read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

String in C

String is a collection of character or group of characters. In array, string of character is terminated by a null value “\0” and enclose between double quote. We can declare...

2 minutes read.

pow() function in C

pow() function is one of the in-built functions present in math.h header file Power function is used to calculate the powers of the given number. The syntax of the power...

3 minutes read.

Star Program in C Language

Star Program in C Star patterns are a sequence of * or any other character used to construct any pattern or any like-square geometric form, triangle, hollow square, pyramid, rhombus, etc.  Many programmers worldwide highly...

4 minutes read.

C Pointers

Pointers in C A pointer is a variable, which contains the address of another variable, i.e., it’s a variable which has the address of another variable as its value. The utilization...

4 minutes read.

Limitations of Synchronisation and Uses of Static Synchronisation in Multithreading

The multithreading component of java is the element around which the idea rotates as it permits simultaneous execution of at least two program pieces for the most significant usage of...

9 minutes read.

Doubly Linked list in C

To know the Doubly Linked List in C, first we should know about how the Linked List works. Linked List The Linked list is the linear data structure. In the Linked...

5 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Null character in C

Introduction The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string...

3 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Else If Ladder in C

What is Else If Ladder: When there are multiple options and a user has to decide from the options, we use Else If Ladder. Basically, it is an extension of if...

3 minutes read.