Bubble sort

 Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here's an example implementation of bubble sort in Python:


python


def bubble_sort(arr):

    """

    Sorts a list of integers using the bubble sort algorithm.

    

    Parameters:

    arr (list): A list of integers.

    

    Returns:

    list: The sorted list of integers.

    """

    n = len(arr)

    for i in range(n):

        for j in range(n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr

In this implementation, we start by initializing a variable n to the length of the input array arr. We then perform n passes through the array, with each pass comparing adjacent elements and swapping them if they are in the wrong order. We do this by iterating over the indices of the array using two nested loops. The inner loop runs from 0 to n - i - 2, which corresponds to the range of indices that still need to be compared in the current pass. If the current element arr[j] is greater than the next element arr[j + 1], we swap them using Python's tuple packing and unpacking syntax.


Here's an example usage of the bubble_sort function:


python


arr = [5, 3, 8, 4, 2]

sorted_arr = bubble_sort(arr)

print(sorted_arr)  # Output: [2, 3, 4, 5, 8]

In this example, we use bubble_sort to sort the input array [5, 3, 8, 4, 2]. The function returns the sorted array [2, 3, 4, 5, 8].

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...