Program to sort a given array using bubble sort
Bubble sort is a simple sorting algorithm. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them.
It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.
Bubble sort can be used to sort a small number of items (where its inefficiency is not a high penalty). Bubble sort may also be efficiently used on a list that is already sorted except for a very small number of elements.
For example, if only one element is not in order, bubble sort will take only 2n time. If two elements are not in order, bubble sort will take only at most 3n time.
#include<iostream.h>
main()
{
int n, a[20],i,j, temp;
cout<<"Enter the size of an array:"; cin>>n;
cout<<"Enter the elements to array:\n";
for(i=0; i<n; i++) cin>>a[i];
cout<<"\n\nElements before sorting:\n";
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
for(i=0; i<n; i++)
{
for(j=0;j<n-1;j++) { if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
cout<"\n\n Elements after sorting:\n";
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
cout<<endl;
return(0);
}
OUTPUT Enter the size of an array: 5 Enter the elements to array: 9 7 3 6 2 Elements before sorting: 9 7 3 6 2 Elements after sorting: 2 3 6 7 9
Algorithm Explanation
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons and swapping.
– After the first traversal only the largest value is correctly placed
– All other values are still out of order
– So we need to repeat this process.
–
– If we have N elements… And if each time we bubble an element, we place it in its correct location…
– Then we repeat the–1 times“bubble. up” process
– This guarantees we’ll correctly place a
• We can use a Boolean variable (Here it is switched) to determine if any swapping occurred during the “bubble up.”
• If no swapping occurred, then we know that the collection is already sorted.
• This Boolean “flag” needs to be reset after
Efficiency Analysis of Bubble sort:
• One traversal = move the maximum element at the end
• Traversal : n –i + 1 operations
• Running time:
(n –1) + (n –2) + … + 1 = (n)by applying+1)the summation/ 2formula=. O(n)


