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

C++ Program to sort an Array by using Bubble sort

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

60 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????

    Reply
    1. Neeraj Mishra

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

      Reply
    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…..";
      …….
      }}

      Reply
      1. 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:

        Reply
  2. neha bhatt

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

    Reply
    1. Admin Post author

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

      Reply
    1. 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.

      Reply
    2. benak

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

      Reply
  3. Rutamvar

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

    Reply
    1. ismaelabdul

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

      Reply
  4. vikram

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

    Reply
      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!

        Reply
  5. 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)

    Reply
  6. 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

    Reply
  7. 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;
    }
    }

    Reply
    1. Admin Post author

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

      Reply
      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??

        Reply
        1. Admin Post author

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

          Reply
        2. Kundan

          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.

          Reply
  8. 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!

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

      Reply
  9. 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!

    Reply
  10. Subhajit Saha

    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;
    }

    Reply
    1. Admin Post author

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

      Reply
      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!

        Reply
        1. Admin Post author

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

          Reply
    2. abdul

      #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;
      }
      }

      Reply
  11. vijay

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

    Reply
  12. 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.

    Reply
  13. 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;
    }

    Reply
  14. Subha

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

    Reply
    1. Admin Post author

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

      Reply
  15. munmaya mohanty

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

    Reply
  16. 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…

    Reply
  17. pnkaj

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

    Reply
  18. 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[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++

    Reply
  19. 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[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();
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *