AlgoFrames

Array after k passes

Standard · Write code · about 10 min

Run exactly k passes of bubble sort on nums and return the array. A pass walks left to right over the unsorted part and swaps each neighbouring pair that is out of order.

If k is at least n - 1, return the sorted array.

Example 1

Input:

[[5,1,4,2,8],1]

Output:

[1,4,2,5,8]

Example 2

Input:

[[5,1,4,2,8],2]

Output:

[1,2,4,5,8]

Constraints

  • 0 ≤ nums.length ≤ 1,000
  • 1 ≤ k ≤ 1,000
  • -1,000 ≤ nums[i] ≤ 1,000

Learn the idea first: Bubble sort, a visual lesson.

More Bubble sort problems