Bubble sort first four pairs of a list

Question:

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=" ")
Asked By: stormy2020

||

Answers:

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()
Answered By: Jiří Baum

You can try this out :(sorting for the first n number of elements)

def bubbleSort(arr,k):

"""
argument arr is list, k is int
store result in res
"""

res = 0
l = len(arr[:k])

for i in range(l-1):
    print(arr[i], end=' ')
    for j in range(l-1):
        if arr[j] > arr[j+1]:
            arr[j], arr[j+1] = arr[j+1], arr[j]

print()
print(arr)
res = arr[0] + arr[-1]

print(res)/return res

=======================================

Inputs :

arr = [64, 34, 25, 12, 22, 11, 90]

k = 4

=================================

OutPuts :

64 25 34

[12, 25, 34, 64, 22, 11, 90]

102

Answered By: Ashish
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.