optimised bubble sort python

Solutions on MaxInterview for optimised bubble sort python by the best coders in the world

showing results for - "optimised bubble sort python"
Carys
02 May 2017
1# Optimized bubble sort in python
2
3
4def bubbleSort(array):
5    
6    # run loops two times: one for walking throught the array
7    # and the other for comparison
8    for i in range(len(array)):
9        
10        # swapped keeps track of swapping
11        swapped = True
12        for j in range(0, len(array) - i - 1):
13
14            # To sort in descending order, change > to < in this line.
15            if array[j] > array[j + 1]:
16
17                # swap if greater is at the rear position
18                (array[j], array[j + 1]) = (array[j + 1], array[j])
19                swapped = False
20                
21                # if there is not swapping in the last swap, then the array is already sorted.
22                if swapped:
23                    break
24
25
26data = [-2, 45, 0, 11, -9]
27bubbleSort(data)
28print('Sorted Array in Ascending Order:')
29print(data)
30