Sort Exercise

Sort Exercise with Python

 

Write a Python program to sort the elements of the following array in ascending order, using the specified pair-wise dealing method:

Array: [86, 3, 9, 15, 6, 7, 10, 18]

– Start by comparing and swapping the first pair of elements.
– Then, compare and swap the second element with the first element.
– Next, compare and swap the third element with the second element, and then with the first element.
– Continue this process, comparing and swapping elements in reverse order until the first element.
– If no swaps are needed in a stage, abandon the entire stage.
– The process stops when no more swaps are required.

Your program should output the sorted array in ascending order.

Expected output

Sorted array in ascending order: [3, 6, 7, 9, 10, 15, 18, 86]

Solution


# Step 1: Initialize the array
arr = [86, 3, 9, 15, 6, 7, 10, 18]

# Step 2 and 3: Implement pair-wise dealing and repeat the process
n = len(arr)
swapped = True
while swapped:
    swapped = False
    for i in range(n - 1):
        if arr[i] > arr[i + 1]:
            arr[i], arr[i + 1] = arr[i + 1], arr[i]  # Swap the elements
            swapped = True

# Step 4: Display the sorted array
print("Sorted array in ascending order:", arr)


We start by initializing the array with the given elements. We then use a “while” loop to perform the pair-wise dealing, swapping elements if they are in the wrong order, and continue the process until no more swaps are needed.
After the loop, we print the sorted array in ascending order.

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart