Search code examples
pythonarrayssortingbubble-sort

Bubble sort first four pairs of a list


How do I use the bubble sort but implement it in such a way it only sorts first 4 pairs of a list? [3, 5, 7, 2, 7, 9, 3, 4, 5, 8]

def bubbleSort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]

arr = [5, 3, 9, 7, 2, 7, 3, 4, 5, 8]
bubbleSort(arr)
 
for i in range(len(arr)):
   print("%d" % arr[i], end=" ")

Solution

  • If you want to stop after 4 swaps, the easiest way is probably to count how many you've done and bail out of the sort when you reach the limit; something like this:

    def bubble_sort(arr, max_swaps=-1):
        if max_swaps == 0:
            return
        n = len(arr)
        for i in range(n):
            for j in range(0, n-i-1):
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                    max_swaps -= 1
                    if max_swaps == 0:
                        return
    
    arr = [5, 3, 9, 7, 2, 7, 3, 4, 5, 8]
    bubble_sort(arr, 4)
    
    for i in range(len(arr)):
       print(arr[i], end=" ")
    print()