Given an array of integers called nums,sort the array in non-decreasing order using the bubble sort algorithm and return the sorted array.
A sorted array in non-decreasing order is an array where each element is greater than or equal to all preceding elements in the array.
Input: nums = [7, 4, 1, 5, 3]
Output: [1, 3, 4, 5, 7]
Explanation: 1 <= 3 <= 4 <= 5 <= 7.
Thus the array is sorted in non-decreasing order.
Input: nums = [5, 4, 4, 1, 1]
Output: [1, 1, 4, 4, 5]
Explanation: 1 <= 1 <= 4 <= 4 <= 5.
Thus the array is sorted in non-decreasing order.
Input: nums = [3, 2, 3, 4, 5]
The bubble sort algorithm sorts an array by repeatedly swapping adjacent elements if they are in the wrong order. The largest elements "bubble" to the end of the array with each pass.
i
from 0 to n-1
.j
from 0 to n-i-1
.arr[j] > arr[j+1]
, swap them. Note: Here, after each iteration, the array becomes sorted up to the last index of the range. That is why the last index of the range decreases by 1 after each iteration. This decrement is managed by the outer loop, where the last index is represented by the variable i
. The inner loop (variable j
) helps to push the maximum element of the range [0...i] to the last index (i.e., index i
).
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Bubble sort Functin
vector<int> bubbleSort(vector<int>& nums) {
int n = nums.size();
// Traverse through the array
for (int i = n - 1; i >= 0; i--) {
// Track if swaps are made
bool didSwap = false;
for (int j = 0; j <= i - 1; j++) {
// Swap if next element is smaller
if (nums[j] > nums[j + 1]) {
swap(nums[j], nums[j + 1]);
didSwap = true;
}
}
/** Break out of loop
if no swaps done*/
if (!didSwap) {
break;
}
}
return nums;
}
};
int main() {
// Create an instance of solution
Solution solution;
vector<int> nums = {7, 4, 1, 5, 3};
cout << "Before Using Bubble Sort: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;
// Function call for Bubble Sort
nums = solution.bubbleSort(nums);
cout << "Array After Using Bubble Sort: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
// Bubble Sort Function
public int[] bubbleSort(int[] nums) {
int n = nums.length;
// Traverse through the array
for (int i = n - 1; i >= 0; i--) {
// Track if swaps are made
boolean isSwapped = false;
for (int j = 0; j <= i - 1; j++) {
// Swap if next element is smaller
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
/** Break out of loop
if no swaps done*/
if (!isSwapped) {
break;
}
}
return nums;
}
public static void main(String[] args) {
// Create an instance of solution class
Solution solution = new Solution();
int[] nums = {7, 4, 1, 5, 3};
System.out.println("Array Before Using Bubble Sort: " + Arrays.toString(nums));
// Function call for Bubble Sort
nums = solution.bubbleSort(nums);
System.out.println("Array After Using Bubble Sort: " + Arrays.toString(nums));
}
}
class Solution:
# Bubble Sort Function
def bubbleSort(self, nums):
n = len(nums)
# Traverse through the array
for i in range(n - 1, -1, -1):
# Track if swaps are made
isSwapped = False
for j in range(i):
# Swap if next element is smaller
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
isSwapped = True
''' Break out of loop
if no swaps done'''
if not isSwapped:
break
return nums
# Main function
if __name__ == "__main__":
# Create an instance of solution class
solution = Solution()
nums = [7, 4, 1, 5, 3]
print("Array Before Using Bubble Sort:", nums)
# Function call for Bubble Sort
sorted_nums = solution.bubble_sort(nums)
print("Array After Using Bubble Sort:", sorted_nums)
class Solution {
// Bubble Sort Function
bubbleSort(nums) {
let n = nums.length;
// Traverse through the array
for (let i = n - 1; i >= 0; i--) {
// Track if swaps are made
let isSwapped = false;
for (let j = 0; j <= i - 1; j++) {
// Swap if next element is smaller
if (nums[j] > nums[j + 1]) {
[nums[j], nums[j + 1]] = [nums[j + 1], nums[j]];
isSwapped = true;
}
}
/** Break out of loop
if no swaps done*/
if (!isSwapped) {
break;
}
}
return nums;
}
}
// Create an instance of solution class
let solution = new Solution();
let nums = [7, 4, 1, 5, 3];
console.log("Array Before Using Bubble Sort:", nums);
// Call the bubbleSort function
nums = solution.bubbleSort(nums);
console.log("Array After Using Bubble Sort:", nums);
Time Complexity: O(N2) for the worst and average cases and O(N) for the best case. Here, N is the size of the array.
Space Complexity: O(1), because Bubble Sort is an in-place sorting algorithm, meaning it only requires a constant amount of extra space for its operations, regardless of the size of the input array.
Q: Can bubble sort handle duplicate elements?
A: Yes, bubble sort can handle duplicate elements. It treats duplicates like any other element and compares them during iterations. Since duplicates are not swapped unnecessarily, their relative order remains unchanged, preserving stability. Example: Input: [4, 2, 4, 1] Output: [1, 2, 4, 4]
Q: What happens if the array is already sorted or reverse sorted?
A: Already Sorted: The algorithm performs a single pass and terminates early if optimized. Without optimization, it will still make unnecessary passes. Reverse Sorted: Bubble sort performs the maximum number of swaps (O(n2)) because every element needs to be repositioned. Example (Reverse Sorted): Input: [5, 4, 3, 2, 1] Output: [1, 2, 3, 4, 5]
Q: Can you modify bubble sort to sort in descending order?
A: To sort in descending order, modify the comparison condition to check if the current element is smaller than the next element. Swap them if so. Example: Input: [4, 2, 9, 1] Process: Compare 4 and 2 → No swap. Compare 2 and 9 → Swap: [4, 9, 2, 1]. Continue until sorted in descending order: [9, 4, 2, 1].
Q: How does bubble sort compare to insertion sort and selection sort?
A: Time Complexity: All three have a worst-case time complexity of O(n2). However, bubble sort generally performs worse due to its many comparisons and swaps. Optimization: Bubble sort can be optimized to terminate early for sorted arrays, while insertion and selection sorts do not inherently have this feature. Stability: Both bubble and insertion sorts are stable (preserve the order of duplicate elements). Selection sort is not stable unless modified.