Bubble Sort

Sorting Algorithms Easy

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.

Examples:

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]

Constraints

  • 1 <= nums.length <= 1000
  • -104 <= nums[i] <= 104
  • nums[i] may contain duplicate values.

Hints

  • Focus on comparing adjacent elements and swapping them if they are in the wrong order. Repeat this until no swaps are needed. After each iteration, the largest element in the unsorted portion moves to its correct position at the end.
  • For Optimization, Think about stopping the algorithm early if no swaps occur during an iteration, indicating the array is already sorted.

Company Tags

AMD Flipkart PayPal ARM Goldman Sachs Zomato Micron Technology Philips Healthcare Shopify Intel Morgan Stanley Cloudflare JPMorgan Chase Roblox Broadcom Target Square Bungie Swiggy IBM KPMG DoorDash OYO Rooms Nutanix Ubisoft TCS Cognizant Accenture Infosys Capgemini Wipro