C++ program to sort an array using bubble sort

This program implements bubble sort in C++.  Bubble sort iterates through the array by considering each pair of elements and swapping them if it is not in the sorted order. This procedure repeats until the entire array is sorted. The program reads the limit of the array into the variable n. The elements are read one by one into the array a[]. Then the program uses a nested for loop to perform bubble sort. After sorting is completed the new array is displayed to the output screen.


Program


// bubble sorting in c
#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10],i,n,j,temp,*p;
          clrscr();
          cout<<"Enter the limit: ";
          cin>>n;
          cout<<"\nEnter the "<<n<<" array elements\n\n";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          p=a;
          for(i=0;i<n;i++)
          {
                   for(j=0;j<n-1-i;j++)
                   {
                             if(*(p+j)>*(p+j+1))
                             {
                                      temp=*(p+j);
                                      *(p+j)=*(p+j+1);
                                      *(p+j+1)=temp;
                             }
                   }
          }
          cout<<"\nsorted array is as follows\n\n";
          for(i=0;i<n;i++)
          {
                   cout<<a[i]<<" ";
          }
          getch();
}



bubble sort in c++
C++ program for bubble sort












Related post: Bubble sort in c

No comments: