Logo

Day 2 - Coding Bubble Sort

⬅ Previous  Home  Next ⮕

Introduction

In this use case, we want to know how to code the Bubble Sort algorithm.

AI used: GPT-4

Prompt:

Write a function that sorts an array using the bubble sort algorithm.

Result:


(python)
  def bubble_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # Swap if the element found is greater than the next element
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example usage:
data = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(data)
print("Sorted array is:", data)

Tips