Tutorialspoint
Problem
Solution
Submissions

Bubble Sort

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program that implements the bubble sort algorithm. The program should sort an unsorted array of integers in ascending order using the bubble sort technique.

Example 1
  • Input: array = [5, 1, 4, 2, 8]
  • Output: [1, 2, 4, 5, 8]
  • Explanation:
    • Step 1: First pass
      • Compare 5 and 1. Swap: [1, 5, 4, 2, 8]
      • Compare 5 and 4. Swap: [1, 4, 5, 2, 8]
      • Compare 5 and 2. Swap: [1, 4, 2, 5, 8]
      • Compare 5 and 8. No swap: [1, 4, 2, 5, 8]
    • Step 2: Second pass
      • Compare 1 and 4. No swap: [1, 4, 2, 5, 8]
      • Compare 4 and 2. Swap: [1, 2, 4, 5, 8]
      • Compare 4 and 5. No swap: [1, 2, 4, 5, 8]
      • Compare 5 and 8. No swap: [1, 2, 4, 5, 8]
    • Step 3: Third pass - No swaps occur, array is sorted
    • Step 4: Return sorted array [1, 2, 4, 5, 8]
Example 2
  • Input: array = [9, 8, 7, 6, 5]
  • Output: [5, 6, 7, 8, 9]
  • Explanation:
    • Step 1: First pass
      • Compare 9 and 8. Swap: [8, 9, 7, 6, 5]
      • Compare 9 and 7. Swap: [8, 7, 9, 6, 5]
      • Compare 9 and 6. Swap: [8, 7, 6, 9, 5]
      • Compare 9 and 5. Swap: [8, 7, 6, 5, 9]
    • Step 2: Second pass - Continue swapping pairs...
    • Step 3: Third pass - Continue swapping pairs...
    • Step 4: Fourth pass - Continue swapping pairs...
    • Step 5: Return sorted array [5, 6, 7, 8, 9]
Constraints
  • 1 ≤ array.length ≤ 10^3
  • -10^6 ≤ array[i] ≤ 10^6
  • Time Complexity: O(n²), where n is the length of the array
  • Space Complexity: O(1)
ArraysAlgorithmsCapgeminiShopify
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two nested loops to iterate through the array.
  • In each iteration of the outer loop, compare adjacent elements in the inner loop.
  • Swap adjacent elements if they are in the wrong order.
  • Optimize by tracking if any swaps were made in a pass - if no swaps, the array is sorted.
  • After each pass, the largest element bubbles up to its correct position.

Steps to solve by this approach:

 Step 1: Loop through the array multiple times.

 Step 2: Compare adjacent elements in the array.
 Step 3: Swap adjacent elements if they are in wrong order.
 Step 4: Use a flag to track if any swaps occurred in a pass.
 Step 5: If no swaps occur in a pass, the array is sorted.
 Step 6: Return the sorted array.

Submitted Code :