Tutorialspoint
Problem
Solution
Submissions

Bubble Sort

Certification: Basic Level Accuracy: 50% Submissions: 4 Points: 5

Write a Java program to implement the Bubble Sort algorithm to sort an array of integers in ascending order.

Example 1
  • Input: nums = [64, 34, 25, 12, 22, 11, 90]
  • Output: [11, 12, 22, 25, 34, 64, 90]
Example 2
  • Input: nums = [5, 1, 4, 2, 8]
  • Output: [1, 2, 4, 5, 8]
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^5 ≤ nums[i] ≤ 10^5
  • Time Complexity: O(n²)
  • Space Complexity: O(1)
ArraysHCL TechnologiesD. E. Shaw
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

  • Compare adjacent elements in the array.
  • Swap elements if they are in the wrong order.
  • Repeat the process for each element of the array.
  • After each pass, the largest element moves to the end.
  • Optimize by reducing the number of comparisons in each subsequent pass.
  • Consider implementing an early termination if no swaps occur in a pass.

Steps to solve by this approach:

 Step 1: Iterate through the array n-1 times (where n is the array length).

 Step 2: For each iteration, compare adjacent elements from index 0 to n-i-1.
 Step 3: If the current element is greater than the next element, swap them.
 Step 4: Keep track of whether any swaps were made in the current pass.
 Step 5: If no swaps occurred in a pass, the array is already sorted, so exit early.
 Step 6: After each pass, the largest unsorted element "bubbles up" to its correct position.
 Step 7: Continue until the entire array is sorted in ascending order.

Submitted Code :