FastPrepBubble Sort

Bubble Sort

Hartford Financial Services logoHartford Financial Services● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Implement bubbleSort(nums) using bubble sort to return the integers of nums in nondecreasing order.

On each left-to-right pass, compare neighboring elements and swap them when the left value is greater. Continue until the array is sorted. Do not replace bubble sort with a built-in sorting routine or a different sorting algorithm.

You may modify nums in place. Return the resulting sorted array, preserving every occurrence of each input value.

Function

bubbleSort(nums: int[]) → int[]

Examples

Example 1

nums = [5,1,4,2,8]return = [1,2,4,5,8]

Repeated neighboring swaps place the smaller values before the larger values.

Example 2

nums = [3,-1,3,0]return = [-1,0,3,3]

Negative values sort first, and both occurrences of 3 remain.

Example 3

nums = [7]return = [7]

A one-element array is already sorted.

Constraints

  • 1 <= nums.length <= 2000.
  • -10^9 <= nums[i] <= 10^9.

More Hartford Financial Services problems

See Hartford Financial Services hiring insights
public int[] bubbleSort(int[] nums) {
    // write your code here
}
nums[5,1,4,2,8]
expected[1,2,4,5,8]
Checking account…