
Problem
Solution
Submissions
Bubble Sort Algorithm
Certification: Intermediate Level
Accuracy: 66.67%
Submissions: 3
Points: 15
Write a Python program that implements the Bubble Sort algorithm to sort a list of integers in ascending order. 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.
Example 1
- Input: [64, 34, 25, 12, 22, 11, 90]
- Output: [11, 12, 22, 25, 34, 64, 90]
- Explanation:
- Step 1: Take the input array [64, 34, 25, 12, 22, 11, 90].
- Step 2: Compare adjacent elements and swap if necessary.
- Step 3: After first pass: [34, 25, 12, 22, 11, 64, 90] (90 is in its correct position).
- Step 4: After second pass: [25, 12, 22, 11, 34, 64, 90] (64 and 90 are in position).
- Step 5: Continue this process for all elements.
- Step 6: Return the sorted array [11, 12, 22, 25, 34, 64, 90].
Example 2
- Input: [5, 1, 4, 2, 8]
- Output: [1, 2, 4, 5, 8]
- Explanation:
- Step 1: Take the input array [5, 1, 4, 2, 8].
- Step 2: Compare adjacent elements and swap if necessary.
- Step 3: After first pass: [1, 4, 2, 5, 8] (5 and 8 are in their correct positions).
- Step 4: After second pass: [1, 2, 4, 5, 8] (4, 5, and 8 are in position).
- Step 5: After third pass: No swaps needed, array is sorted.
- Step 6: Return the sorted array [1, 2, 4, 5, 8].
Constraints
- 1 ≤ len(arr) ≤ 10^3
- -10^6 ≤ arr[i] ≤ 10^6
- Time Complexity: O(n²), where n is the length of the array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use nested loops to compare adjacent elements
- Swap adjacent elements if they are in the wrong order
- After each pass, the largest element is guaranteed to be at the end
- Optimize by stopping the algorithm if no swaps are made in a pass
- The outer loop can run for n-1 iterations, where n is the length of the array
- The inner loop can run for n-i-1 iterations per outer loop iteration i