|
| 1 | +'''Bubble Sort |
| 2 | +Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. |
| 3 | +Example: |
| 4 | +First Pass: |
| 5 | +( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. |
| 6 | +( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 |
| 7 | +( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 |
| 8 | +( 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. |
| 9 | +
|
| 10 | +Second Pass: |
| 11 | +( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) |
| 12 | +( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 |
| 13 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) |
| 14 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) |
| 15 | +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. |
| 16 | +
|
| 17 | +Third Pass: |
| 18 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) |
| 19 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) |
| 20 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) |
| 21 | +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )''' |
| 22 | + |
| 23 | +# Python program for implementation of Bubble Sort |
| 24 | + |
| 25 | +def bubbleSort(arr): |
| 26 | + n = len(arr) |
| 27 | + |
| 28 | + # Traverse through all array elements |
| 29 | + for i in range(n): |
| 30 | + |
| 31 | + # Last i elements are already in place |
| 32 | + for j in range(0, n-i-1): |
| 33 | + |
| 34 | + # traverse the array from 0 to n-i-1 |
| 35 | + # Swap if the element found is greater |
| 36 | + # than the next element |
| 37 | + if arr[j] > arr[j+1] : |
| 38 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 39 | + |
| 40 | +# Driver code to test above |
| 41 | +arr = [64, 34, 25, 12, 22, 11, 90] |
| 42 | + |
| 43 | +bubbleSort(arr) |
| 44 | + |
| 45 | +print ("Sorted array is:") |
| 46 | +for i in range(len(arr)): |
| 47 | + print ("%d" %arr[i]), |
0 commit comments