Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

C Program For Bubble Sorting: Bubble Sort in C

Updated on 15 November, 2022

7.5K+ views
7 min read

Introduction

The sorting of an array holds a place of immense importance in computer science. Its utility is noticed when there is a need to arrange data in a specific order. There are different kinds of sorting algorithms. The most common and widely used sorting algorithm is the Bubble Sort.

Check out our free courses to get an edge over the competition. 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Bubble Sort in C

The technique that is used for sorting in Bubble sort is simple and easy to understand. All it does is compare the current element with the next element and swap it if it is greater or lesser as dictated by the condition. The algorithm is very accurate. Each time an element is compared with other elements until its place is found, it is called a pass.

This algorithm is comparable to bubbles in water as it filters out the top of the array-like bubbles. Among all the algorithms used for sorting, Bubble sort is the easiest and the slowest with time complexity of O(n^2). However, the algorithm can be optimized through the use of a flag variable that exits the loop when swapping is completed. The best case for Bubble sort can be O(n) when the array is sorted.

Check out upGrad’s Advanced Certification in Blockchain

For example, let us take an unsorted array of five numbers as given below

13, 32,26, 34,9

Bubble sort will begin considering the first two elements, and it will compare them to check which one is greater. In this case, 32 is greater than 13. So this portion is already y sorted. Next, we compare 32 with 26. So we find that 32 is greater than 26, so they must be swapped. The new array will look like

13, 26, 32,34,9

Next, we compare 32 and 34. We know that they are already sorted. Thus we move to the last two variables 34 and 9. Since 34 is greater than 9, they have to be swapped.

We swap the values and come to the end of the array after the first iteration. Now the array will look like

13, 26. 32,9,34

After the second iteration, the array will look like

13, 26, 9,32,34

After the third iteration, the array will become

13,9,26,32,34

After the fourth iteration, the array will be completely sorted

9, 13,26,32,34       

Must Read: Project Ideas in C

The algorithm

Here we are assuming that the array has n elements. Further, we assume that the exchange values function is swapping all the values to make the array numbers in sorted order.

Check out upGrad’s Advanced Certification in Cloud Computing

 start BubbleSort (array)
 for all elements of the list
 if array[i]> array[i+1]
 exchange values(array[i], array[i+1] )
end if
end for
return array
end Bubble Sort

Read: Sorting in Data Structure: Categories & Types

Pseudocode

It is evident in the above algorithm that there is a comparison between each pair of the array element until the whole array is sorted in ascending order. It may result in a few complexity issues, such as the algorithm’s outcome when the array is already sorted in ascending order. For easing out the issue, we will be using one flag variable, which enables us to see if there has been any swapping. If no more swapping is needed, we will come out of the inner loop.

The pseudocode for the BubbleSort algorithm can be written as follows

procedure BubbleSort (array: items in the array)

iterate= array.count;  

for k=0 to iterate-1 do:

flag= false

for l=0 to iterate-1 do:

if (array[l]> array[l+1]) then

exchange values(array[l], array [l+1])

flag=true

end if

end for

If (not swapped) then

Break

End if

End for

End procedure return array

Let us try out a sample program of bubble sort in C:

# include<stdio.h>

void main

{

   int array [10], i, j, num

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

   {

      scanf(“%d”, &array[i])

   }

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

         {

           for(j=0;j<=9-i;j++)

            {

                if(array[j]>array[j+1])

                   {

                       num= array[j];

                        array[j]=array[j+1];

                       array[j+1]=num;

                   }

             }

          }

  printf(“The sorted array is /n”);

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

       {

          printf(“%d ”,&array[i])

        }

}

As shown in the sample, this bubble sort algorithm accepts 10 numbers from the user and stores it in the array. In the next part, there are two for loops. The outer loop runs for I value, equalling zero to less than equal to nine. The outer loop’s function is to take care of all the elements of the value that have to be compared with other elements.

There is another loop inside the outer loop. It starts from j=0 and runs until it is lesser than or equal to eight. Inside, there is a conditional if statement which compares and checks if array[j] is greater than array [j+1]. If the condition is satisfied the values of array[j] and array [j+1] are swapped with each other.

A variable by the name of num is used for this purpose. First array[j] is assigned to num, then array[j+1] is assigned to array[j], and finally num is assigned to array[j+1]. This process will continue until all the elements in the array are sorted in increasing order. After that, the sorted array is printed. 

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Optimized implementation of Bubble Sort

We have an optimized algorithm for bubble sort for improving the results. The use of a flag variable does the optimization. The flag variable will hold 1 if there is a swapping else it will break out from the loop. Below is the optimized bubble sort program in C.

#include<stdio.h>

void main

{

   int array [10], i, j, num, flag=0;

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

   {

      scanf(“%d”, &array[i])

   }

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

         {

           for(j=0;j<=9-i;j++)

            {

                if(array[j]>array[j+1])

                   {

                       num= array[j];

                        array[j]=array[j+1];

                       array[j+1]=num;

                        flag=1;

                   }

                 if(! flag)

                  {

                          break;

                  }

             }

          }

  printf(“The sorted array is /n”);

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

       {

          printf(“%d ”,&array[i])

        }

}

The given program executes in a way that is similar to the normal bubble sort program. The only change is the use of the flag variable. Initially, the flag is set to 0. However, if a swapping takes place, the flag becomes 1. It implies that the array still requires one more checking. On the other hand, if the flag is not 1, implying that swapping has not taken place, we exit from the inner loop, assuming that the array is already sorted. Once executed, we will get the same result as the normal Bubble sort.

Time Complexity

The best-case time complexity for Bubble sort is O(n). It happens when the array is already sorted. The worst case is O(n*n) when the array has not been sorted.  

Read: Top 12 Pattern Programs in Java You Should Checkout Today

What Next?

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. Why is sorting necessary?

Sorting is a method of arranging the items in a set in a specific order. In other words, it arranges a vast number of elements in a certain order, such as alphabetical, highest-to-lowest value, or shortest-to-longest distance. The input is sorted in the output. In computer science, sorting is one of the most significant categories of the algorithm, and a lot of studies have gone into it. It is frequently used for database algorithms and search operations since it is easier and faster to identify things in a sorted list. In software, sorting can be used to sort an array for subsequent searching or output to an ordered file or report.

2. Why is Bubble sort preferred in sorting algorithms?

One of the most basic types of sorting in programming is the bubble sort. Bubble sort algorithms run through a group of data (usually numbers) and restructure them one by one into ascending or descending order. Bubble sort gets its name from how smaller and bigger pieces bubble to the head of a dataset. For the opposite reason, bubble sort is also known as sinking sort since certain data pieces sink to the bottom of the dataset. The simplicity of bubble sort is one of its strongest features. It has only a few lines of code, is simple to understand, and can be used anywhere in your software. For bigger collections of numbers, however, it is exceedingly wasteful and should be avoided.

3. What are the uses of C programming?

C programming is used in a variety of sectors and can be utilized in numerous ways since it has built-in functions and operators that can be used to address a variety of complicated issues. C is a language that combines the features of both low-level and high-level languages. It's utilized in embedded systems and for the creation of system applications. It's also used in the creation of desktop apps and the vast majority of Adobe products. C is a programming language that is used to create browsers and their extensions. It's also used in the creation of databases, such as MySQL and operating systems. It's used to make compilers and in the Internet of Things applications.

RELATED PROGRAMS