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++
#include<iostream> using namespace std; int main() { int a[50],n,i,j,temp; cout<<"Enter the size of array: "; cin>>n; cout<<"Enter the array elements: "; for(i=0;i<n;++i) cin>>a[i]; for(i=1;i<n;++i) { for(j=0;j<(n-i);++j) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } cout<<"Array after bubble sort:"; for(i=0;i<n;++i) cout<<" "<<a[i]; return 0; }
Output
If you found anything incorrect or have doubts regarding above bubble sort in C++ program then comment below.
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????
There was a little mistake in the logic, I have fixed the issue. Thanks for telling the error 🙂
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…..";
…….
}}
Yu right
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:
1 2 3 5 6
why n-1-i
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.
Then it will stop at iteration 2
why do we use 2 for loops in bubble sort program?
please tell!
Because each element is compared with all other elements. Outer loop indicates each element while inner loop indicates comparisons.
Why not u used instead of namespace.Std;.
Only the first two elements are sorted. Help please!
pdh liya kro
try agian
what is the significance of using namespace std at line no 2
thats as we are using C++ compiler
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.
Thanks Vekant for such a nice explanation.
because he has used code blocks so by using namespace std u dont have to put std::before every cin and cout statement.
Thanks, what a great tutorial
Why in the first loop it is (i=0;i<n) and the second time it is (i=1;i<n)?
the second time is to get the 1st element in the array
dear sir there are no change after sorting.
the elements are print in same order in which I have entered
please help…..
It must work, what are the elements that you have entered?
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!
lol it worked for me
can we use while loop instead of inner loop???
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)
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
Second for loop doesn’t have braces
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;
}
}
why does you take a[50]
it must be a[n]
array size can’t be variable, it should be constant.
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??
In that case you have to dynamically allocate memory at run time.
U have to allocate memory bytes to array by using the constant value like int a[100] 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[60] 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.
Thank You it works fine!
Nice program, thank you!
sir output is not shown
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!
In this case both ++i and i++ will do the same work. Problem occurs when we are using it in some arithmetic expression.
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!
There is no such condition in program.
why its not working???
#include
using namespace std;
int main()
{
int a[10],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;
}
Your code is wrong, just check the code that I have shared in this article.
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!
Yes it will work, when loop body contains only one statement then brackets are optional.
#include
using namespace std;
void bubblesort( int arr[ ], int size);
int main(){
int array [100];
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;
}
}
sir explain deeply for ( j = 0; j a [ j + 1])
can we use while loop instead of for loop. please share the coding using while loop.thanks in advance.
ya we can use while loop …but for loop is easier for to use for this purpose
Hi can anyone post the program of mereg sort
the program which you are mention is wrong
cout<<"enter the value of arry"<>a[i];
then we will use the for loop.
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;
}
Is there any difference between i++ and ++i inside the for loop?
It doesn’t make any difference in for loop but both are different in case of any other expression.
How the inner and outer loop works …I’m totally confused..
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…
write a c program to implement following shorting technique to arrange element into accending order1)bubble shortin 2)insertion shorting
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[20];
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++
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[100],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();
}
Sir why. Blank quotation marks in last cout statement ending
To give space after each element in output.
we can also use i++ and j++ instead of ++i and ++j
i am in class 11 and just started learning c++ so can u plz tell me why have u used ++i & not i++
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…
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
You are allocating an array of a[50] and taking 5 elements.
Declare an array of a[n-1] after taking number of elements.
can you help me joining linear and binary searching, selection insertion and bubble sorting using if else or do while
why we use new loop for displaying after bubble sort ????
Hi ! Every one. I’m new ,
I’m in 11 class and just started c++.
So plx can you tell me what is temp=a[j];
And why we use temp
i think this once more flexible
#include
using namespace std;
int main(){
cout<<"Let's start bubble sort program"<<endl;
int i,j,n;
cout<<"Enter the size of array"<>n;
for(i = 0; i>arr[i];
}
for(i = 0; i<n;i++){
for(j = i+1; j<=n; j++){
int temp ;
if(arr[i]<arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
cout<<"After shorting the whole program let's display the output.."<<endl;
for(i =0; i<=n;i++){
cout<<" "<<arr[i]<<endl;
}
return 0;
}
can someone help me ? i cant figure out how to fix the error
#include
using namespace std;
void bubleSort(int *a, int n);
void display(int *a, int n);
int main()
{
int n;
int *ptr;
cout <>n;
ptr=new int[n];
cout << "Enter the values … \n";
for (int i=0; i> arr[i];
display(a, n);
bubleSort(num, dysize);
}
void bubleSort(int *a, int n)
{
int last = n – 1;
cout << "\nBubble Sort…" << endl << endl;
for (int i = 0; i i; j–)
if (a[j – 1] > a[j])
swap(a[j], a[j – 1]);
cout << "Pass " << i + 1 << "…." << endl;
display(a, n);
cout << endl;
}
}
void display(int *a, int n)
{
}