on Leave a Comment

C++ Program for Bubble Sort

This c++ program sorts an array of n elements using bubble sort technique. In bubble sort technique, adjacent elements of array is compared. In this program, first you have to enter size of an array, then you have to enter elements of array using keyboard and finally sorted array is displayed on the screen.

C++ Program for Bubble Sort

#include<iostream>
using namespace std;
int main()
{
    int arr[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>>arr[i];
    for(i=1; i<n; i++)
    {
        for(j=0; j<(n-i); j++)
            if(arr[j]>arr[j+1])
            {
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
    }
    cout<<"Sorted Array: ";
    for(i=0; i<n; i++)
        cout<<arr[i]<<"  ";
    return 0;
}

OUTPUT 1:

Enter the size of array: 3
Enter the array elements: 8 6 1
Sorted Array: 1  6  8

OUTPUT 2:

Enter the size of array: 5
Enter the array elements: 9 5 6 4 2
Sorted Array: 2  4  5  6  9

0 comments:

Post a Comment