Step-by-step example:
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) ( 1 4 2 5 8 )
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Algorithm For Bubble Sort:
/* Double-Click To Select Code */ Step 1: Repeat Steps 2 and 3 for i=1 to 10 Step 2: Set j=1 Step 3: Repeat while j<=n (A) if a[i] < a[j] Then interchange a[i] and a[j] [End of if] (B) Set j = j+1 [End of Inner Loop] [End of Step 1 Outer Loop] Step 4: Exit
Optimized Algorithm For Bubble Sort:
/* Double-Click To Select Code */ procedure bubbleSort( A : list of sortable items ) n = length(A) repeat swapped = false for i = 1 to n-1 inclusive do if A[i-1] > A[i] then swap(A[i-1], A[i]) swapped = true end if end for n = n - 1 until not swapped end procedure
C Program For Bubble Sort:
/* Double-Click To Select Code */ #include<stdio.h> #include<conio.h> void main() { int i,n,temp,j,arr[25]; clrscr(); printf("Enter the number of elements in the Array: "); scanf("%d",&n); printf("\nEnter the elements:\n\n"); for(i=0 ; i<n ; i++) { printf(" Array[%d] = ",i); scanf("%d",&arr[i]); } for(i=0 ; i<n ; i++) { for(j=0 ; j<n-i-1 ; j++) { if(arr[j]>arr[j+1]) //Swapping Condition is Checked { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } printf("\nThe Sorted Array is:\n\n"); for(i=0 ; i<n ; i++) { printf(" %4d",arr[i]); } getch(); }
Output of Program:
Please Comment If You Liked This Post !!
This article uses material from the Wikipedia article Bubble_Sort which is released under the Creative Commons Attribution-Share-Alike License 3.0
Do you like this post? Please link back to this article by copying one of the codes below.
URL: HTML link code: Forum link code: