# Program for Bubble Sort in C++

In this article you will get program for bubble sort in C++.

Bubble sort is a sorting technique in which each pair of adjacent elements are compared, if they are in wrong order we swap them. This algorithm is named as bubble sort because, same as like bubbles the smaller or lighter elements comes up (at start) and bigger or heavier elements goes down (at end). Below I have shared a program for bubble sort in C++ which sorts a list of numbers in ascending order.

Also Read:  Program for Quick Sort in C++

## Program for Bubble Sort in C++

Output If you found anything incorrect or have doubts regarding above bubble sort in C++ program then comment below.

## 68 thoughts on “Program for Bubble Sort in C++”

1. PreejaAkhil

The input array does not contain the element 7 and the output array missing 23 which is given in the input.. Y its coming so????

1. Neeraj Mishra

There was a little mistake in the logic, I have fixed the issue. Thanks for telling the error 🙂

2. Suprith

Actually the input is wrong ,see this is correct one
for(i=0;I<n;I++)
{
for(j=0;j<n-1-i;j++)
{
t=….
……..
…….
}
for(k=0;k<n!k++)
cout<<"sorted…..";
…….
}}

1. ankit

Yu right

2. RD

This is what I thought it should be, but this is not working…It doesn’t even give me the unsorted array or a partially sorted one when I print the array after the sorting part.
My output screen is like:
Enter size of array.
5
Enter elements of the array.
5
6
2
3
1
The sorted array is:

3. achhaya

why n-1-i

1. samwel

because on comparing the room of arrays where by your data are random placed,the last comparison should be n-1 with n, so you can’t write n since n will not have another last room to compare with because n itself is a last one.

2. neha bhatt

why do we use 2 for loops in bubble sort program?
please tell!

1. Admin Post author

Because each element is compared with all other elements. Outer loop indicates each element while inner loop indicates comparisons.

1. Kundan

Why not u used instead of namespace.Std;.

3. Katrina

Only the first two elements are sorted. Help please!

1. konika

pdh liya kro

2. Zeeshan Ahmad

try agian

4. ritu

what is the significance of using namespace std at line no 2

1. Biswajeet

thats as we are using C++ compiler

2. Venkat Vadlamani

A namespace is a declarative region; it helps is used to organise the code. I suppose you can observe the 8th line of the code; the syntax which is derived from .

std::cout<<"Enter the size of an array: ";

This part of the code is the actual way of writing, but using the standard namespace (std) we can eliminate "std::" elsewhere in the code, i.e., the compiler automatically used std:: where ever it is necessary.

Perhaps, it is a very late answer, you've most probably aced the programming language, but I hope it will be helpful for someone else who is reading this comment.

1. Admin Post author

Thanks Vekant for such a nice explanation.

3. benak

because he has used code blocks so by using namespace std u dont have to put std::before every cin and cout statement.

5. Aamir

Thanks, what a great tutorial

6. Rutamvar

Why in the first loop it is (i=0;i<n) and the second time it is (i=1;i<n)?

1. ismaelabdul

the second time is to get the 1st element in the array

7. vikram

dear sir there are no change after sorting.
the elements are print in same order in which I have entered
please help…..

1. Admin Post author

It must work, what are the elements that you have entered?

1. Dwijesh Gowda

hmm basically i see the problem instead of giving an output as a[j] its written in the program as a[i]. this is the error! cheers if it helped!

2. benak

lol it worked for me

8. usman

can we use while loop instead of inner loop???

9. Fahad Khalil

Outer loop indicates each element while inner loop indicates comparisons.

Since outer loop starts with i=1 & i<n then won't it make the loop run n-1 times only…
I think to initialise i=1 is necessary because of j<n-1 factor at the inner loop…

So shouldn't the outer loop be like
(i=1:i<=n:++I)

10. Amid

Dear sir, can you please rewrite the program printing the array step by step, passes by passes and rounds by rounds. And can you please explain to me whats the difference between the two. I just really need to learn more in programming. If you’re not to busy sir/maam

11. Nivn

Second for loop doesn’t have braces

12. nish

is this correct for bubble sort?
void sort(int arr[],int n)
{
for(int i=0;i<n;i++)
{ for(int j=0;jarr[j+1])
{ int temp= arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}

13. yankee

why does you take a
it must be a[n]

1. Admin Post author

array size can’t be variable, it should be constant.

1. Chayan

But why the array size can’t be variable??
If i take the array size of 50, I cannot sort more than 50 elements….so if i want to have array size of my accordance what should i do??

1. Admin Post author

In that case you have to dynamically allocate memory at run time.

2. Kundan

U have to allocate memory bytes to array by using the constant value like int a in this we are allocating the 200 bytes of memory To our array but when we use any variable then computer can’t able to understand that how much memory bytes should be allocated to that particular array.So why we have to ask the computer that i want to enter 10,20 element or as ur prograame reqd.Once u declare int a computer allocate u120 bytes memory.Now its depend on u ,u can enter all 60 element or less than 60 .If u enter 40 elements it will take 80 bytes of memry remaining 40 bytes of memory can not be used by any other file it is only for element of a.

14. Adil Raza

Thank You it works fine!

15. mm

Nice program, thank you!

16. Bakhtaver Singh

sir output is not shown

17. Anurag

Sir, in the loops ain”t we supposed to be using “i++” instead of “++i”? Because, in case of prefix (++i), the value of i gets incremented even before a single iteration!

1. Admin Post author

In this case both ++i and i++ will do the same work. Problem occurs when we are using it in some arithmetic expression.

18. Kaylio

Hi!

I’m sorry, but what does

for(i=0;i>a[i];

mean? The first input gives the array size, what does this second do? I know it’s to collect all the numbers for the array, but what’s the a[i] for? Thank you!

1. Admin Post author

There is no such condition in program.

19. Subhajit Saha

why its not working???

#include

using namespace std;

int main()
{
int a,size,i,j,temp;
cout<>size;

cout<<"Enter the array\n";
for(i=0;i>a[i];

for(i=1;i<size;++i)
{
for(j=0;ja[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}

cout<<"The sorted array is"<<endl;
for(i=0;i<size;i++)
cout<<a[i]<<"\t";
return 0;
}

1. Admin Post author

Your code is wrong, just check the code that I have shared in this article.

1. Grace Salibay

Sir, I just want to clarify if the code will still work even though the third for loop hadn’t had brackets? I don’t have codeblocks right now since the compiler was broken. Thank you!

1. Admin Post author

Yes it will work, when loop body contains only one statement then brackets are optional.

2. abdul

#include
using namespace std;
void bubblesort( int arr[ ], int size);
int main(){
int array ;
int size;
cout<<" this program can sort the elements : "<<endl;
cout<<" enter the size of array : "<>size;
cout<<" enter nuber of elements : "<<endl;
for (int i = 0; i<size; i++) {

cout<<" element no : "<<i+1<>array[i];

}
cout<<" brfore sorting your elements are : "<<endl;;
for (int i = 0; i<size; i++) {
cout<<" array["<<i<<"] = "<<array[i] ;
cout<<endl;
}
bubblesort(array, 4); //functon call
return 0;
}
void bubblesort( int arr[ ], int size)
{
int temp = 0;
int i, j;
for (i= 1; i<size; i++) {
for (j = 0; j<(size-i); j++) {
if (arr[j]<arr[j+1]) {
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]= temp;
}
}
}
cout<<" array after sorting : "<<endl;
for (i = 0 ; i<size; i++) {
cout<< "array["<<i<<"] = "<<arr[i] ;
cout<<endl;
}
}

20. alfa

sir explain deeply for ( j = 0; j a [ j + 1])

21. vijay

can we use while loop instead of for loop. please share the coding using while loop.thanks in advance.

22. ramraj

Hi can anyone post the program of mereg sort

23. muhammad Ibrar

the program which you are mention is wrong
cout<<"enter the value of arry"<>a[i];
then we will use the for loop.

24. blue

int sortlist(vector list){
bool flag = true; // added in case of event where no swaps are made, therefore sorted.

for(int pass=0; pass<list.size() && flag; pass++){
cout<<"Pass:"<<list[pass]<<endl<<"Pos:";
flag = false;

for(int pos=0;pos<list.size();pos++){
cout<<list[pos]<<" ";
if(list[pass]<list[pos]){

int tempvar=list[pass];

list[pass] = list[pos];
list[pos] = tempvar;
flag=true;
}

}
cout<<endl<<endl;
}

cout<<"Rearranged List:";
for(int pos=0;pos<list.size();pos++){
cout << list[pos]<<" ";
}
return 0;
}

25. Subha

Is there any difference between i++ and ++i inside the for loop?

1. Admin Post author

It doesn’t make any difference in for loop but both are different in case of any other expression.

26. munmaya mohanty

How the inner and outer loop works …I’m totally confused..

27. jiya

if i have to show the comparison in each pass and also want to show the intermediate result then what will be the code???
reply asap…

28. pnkaj

write a c program to implement following shorting technique to arrange element into accending order1)bubble shortin 2)insertion shorting

29. DEVANSH

Write a menu driven program in C++ to perform the following functions on a binary file “BOOK.DAT” containing objects of the following class:
class Book
{ int BookNo;
char Book_name;
public:
// function to enter book details
void enterdetails();
//function to display Book details
void showdetails();
//function to return Book_no
int Rbook_no() {return Book_no;}
//function to return Book_name
int Rbook_name() {return Book_name;}

};

1. Append Records
2. Modify a record for a given book no.
(Use seekg(), tellg() for this purpose)
3. Delete a record with a given book no.
4. Search for a record with a given Book name
5. Display a sorted list of records (sort on Book No.)
6. Display a sorted list of records (Sort on Book Name)
Note: (i) Use dynamic array for sorting of the file.
(ii) Use gotoxy() to display the formatted reports.
(iii) The program should be password protected.

How To Proceed with part 6 in turbo c++

30. RD

Can anybody help me find what’s wrong with my program?? It seems to be correct during dry run but doesn’t give the required output in practice…

#include
#include
void main()
{
clrscr();
int a,n,i,j;
cout<>n;
cout<<"Enter elements of the array.\n";
for(i=0;i>a[i];
cout<<"The sorted array is:\n";
for(i=0;i<n-1;i++)//Here i controls the number of elements from the end that are already sorted
{
for(j=0;ja[j=1])
{
a[j]=a[j]+a[j+1];
a[j+1]=a[j]-a[j+1];
a[j]=a[j]-a[j+1];
}
}
}
for(i=0;i<n;i++)
{
cout<<a[i]<<"\n";
}
getch();
}

31. Aditya

Sir why. Blank quotation marks in last cout statement ending

1. Neeraj Mishra Post author

To give space after each element in output.

32. monica

we can also use i++ and j++ instead of ++i and ++j

33. pratyusha bhattacharjee

i am in class 11 and just started learning c++ so can u plz tell me why have u used ++i & not i++

1. Shubh Gupta

Well, both i++ & ++i Are increment operators, here you can use any of them…
both will increase value by one but if you add it before the program i.e. ++i will execute a bit more faster as it will immediately increase value of i rather than doing after a few nano seconds, here it makes only a little difference, you may do it anyway…

34. Ali

Requirements:
1) Write a complete program that generates an array of 20 random integers in the range
0 to 99, and sorts the array using the given code.
2) When the program starts execution, it should ask the user whether a checkpoint
should be saved. If the user chooses to save checkpoint, the program should ask about
the number of passes of Bubble Sort after which the checkpoint will be saved.
Checkpoint should be saved in a text file.
3) When the program starts execution, it should also ask the user if a previously saved
checkpoint should be restored. If the user chooses to restore a checkpoint, the
program should allow the user to select the checkpoint file, and restore the saved
checkpoint. After that, the program execution should begin normally.

please help

35. Sikandar

You are allocating an array of a and taking 5 elements.
Declare an array of a[n-1] after taking number of elements.

36. hayat

can you help me joining linear and binary searching, selection insertion and bubble sorting using if else or do while

37. Abubaker

why we use new loop for displaying after bubble sort ????

This site uses Akismet to reduce spam. Learn how your comment data is processed.