×

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

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

Union in C

Union is a user-defined data type that is used to hold the different types of elements like structure. In union, all members share the same memory location. Syntax: union [union name] { ...

1 minute read.

For Loop in C

The Syntax of For Loop for (initialization statement; test expression; update statement) {     /* main body of the FOR loop */ } How does For loop work? In for loop, the initialization command is...

3 minutes read.

Garbage in C

Garbage in C The C programming language is a perfect fit for embedded systems as it provides low level control, structured programming, and portability. On the contrary, it does not provide...

3 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Bigint (BIG INTEGERS) in C with Example

The maximum number of digits that a long, long int can have in C/C++ is 20. The issue is how to store the 22-digit number, which is difficult to do...

9 minutes read.

Dos.h Header File in C Language

Dos.h is a header file in C. Interrupt handling, sound generation, date and time functions, and other tasks can be performed using the functions in this library. This is exclusive to...

4 minutes read.

Difference between rand() and srand() function in C

What is the rand()? The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 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.

Goto and Labels in C

Introduction Goto in C: The goto statement is known as the jump statement in C. The goto is used to transfer the control of a program to a predefined label. The goto...

3 minutes read.

getc() function in C

Getc is one of the file handling technique in C. The Getc() is a C library function gets the next character or new characters  from the specific stream and supports...

4 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.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

C Program to Find Largest Number Using Dynamic Memory Allocation

This tutorial will teach us how to locate the highest number a user has ever input into a dynamically allocated memory. C Program: #include <stdio.h> #include <stdlib.h> int main ()  {   int no;   double *data_n;   printf...

1 minute read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.