Saturday, 18 November 2017

C++ Program to Implement Bubble Sort


Code:

#include   iostream

using namespace std;

// Sort arr[] of size n using Bubble Sort. 
void BubbleSort (int arr[], int n)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n-i-1; ++j)
{
// Comparing consecutive data and switching values if value at j > j+1.
if (arr[j] > arr[j+1])
{
arr[j] = arr[j]+arr[j+1];
arr[j+1] = arr[j]-arr[j + 1];
arr[j] = arr[j]-arr[j + 1];
}
}
// Value at n-i-1 will be maximum of all the values below this index.
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<
cin>>arr[i];
}

BubbleSort(arr, n);

// Display the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
        cout<<"->"<

return 0;
}


Output:

Case 1:(average case)

Enter the number of data element to be sorted: 5
Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206

Sorted Data ->2->35->451->998->1206


Case 2:(best case)

Enter the number of data element to be sorted: 5
Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565

Sorted Data ->2->332->456->1024->16565


case 3: (worst case)

Enter the number of data element to be sorted: 5
Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1

Sorted Data ->1->86->332->564->99845


More C++ Programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...