Bubble Sort is a sorting mechanism that utilizes repeated swapping of adjacent values in an array to achieve a sorted order of elements.
The Bubble Sort Algorithm keeps swapping elements till the largest element in the array reaches the last position in the array and then goes on to the next element in the array. This element in turn again swapped and placed according to its value in reference to the last set of elements already sorted.
The following steps show how Bubble Sort is done.
The worst and average-case time complexities of Bubble Sort are both O(n2). The best-case however, where all the elements are already sorted, is O(n). Bubble Sort is an in-place sorting algorithm and no extra memory space is required.
Assumptions: 'array' is an array with 10 numerical elements in random order
BubbleSort( arguments: array )
The Python 3 code for the Bubble Sort function is as follows
def BubbleSort(array): n = len(array) - 1 while n >= 1: i = 0 while i < n: if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] i = i + 1 n = n - 1
The complete program, after implementation and compilation is
def BubbleSort(array): n = len(array) - 1 while n >= 1: i = 0 while i < n: if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] i = i + 1 n = n - 1 array1 = [9, 8, 6, 7, 5, 4, 1, 3, 2] BubbleSort(array1) print(array1)
the output of which is
[1, 2, 3, 4, 5, 6, 7, 8, 9]