Write a method that takes in an array of int
s and uses
the Bubble Sort algorithm to sort the array 'in place' in ascending order. The method should return the same, in-place sorted array.
Note: Bubble sort is one of the most inefficient ways to sort a large array of integers. Nevertheless, it is an interview favorite. Bubble sort has a time complexity of O(n2). However, if the sample size is small, bubble sort provides a simple implementation of a classic sorting algorithm.
bubbleSortArray({5,4,3}) -> {3,4,5}
bubbleSortArray({3}) -> {3}
bubbleSortArray({}) -> {}
{} -> [Empty] Array
tail
index to keep a track of the elements that have been bubbled(sorted) to the end. The outer loop should be a reverse loop that decrements the tail
index after each iteration. for
loop should iterate from the start to the tail
bubbling each element to the end by swapping adjacent numbers if required. Use a temp variable to do the swap.
1) Use an outer reverse for
loop to iterate over the array, from arr.length - 1
to 0
, keeping the index at the tail
position.
2) Iterate the inner for
loop over the array till the last unsorted element of the array - the tail
position.
3) Swap if the next element is smaller than the current element arr[j] > arr[j+1]
.
public static int[] bubbleSortArray(int[] arr){ return arr; }
C
Java
Python