Senior Software Engineer Interview Questions and Answers
The basic sorting method known as a bubble sort involves periodically switching nearby entries in an array. Because of its high average and worst-case temporal complexity, this is not appropriate for processing large amounts of data. Bubble sort tries to solve this by first comparing adjacent elements. If the element being compared is smaller than a given threshold value, the larger one is swapped with it and vice versa if the element being compared is larger than that threshold value. Thus samples are evaluated using less space than they used to be before the swap process started, hence making this algorithm faster than its variants such as heap sort or quick sort.
Implementation of bubble sort
Our example uses an unsorted array. Because bubble sort requires O(n2) time, we’re making it concise and direct.
The first two items in a bubble sort are compared to see which one is bigger in the beginning.
Value 33 is bigger than 14, therefore, which is already in sorted places in this instance.
We now compare 33 with 27. Since 27 is less than 33, these two numbers must be switched.
The resulting array should seem as follows:
Let’s next evaluate 33 and 35. These are already in ordered places, as we discover.
Afterward, we get to the further two values: 35 and 10.
However, we knew that 10 is less than 35. So they really aren’t sorted as a result.
The values are switched. We discover that the array’s end has been approached. The array shall seem as follows after the first iterative process:
We are specifically demonstrating the state of an array following each loop right now. After the second revision, it ought to resemble this:
Remember that at least a single value shifts at the end of every iteration.
Additionally, bubble sorts discover that an array is fully sorted when no switch is necessary. shown here
Program :
import java.util.Arrays; public class BubbleSort { public static void main(String args[]) { bubbleSort(new int[] { 20, 12, 45, 19, 91, 55 }); bubbleSort(new int[] { -1, 0, 1 }); bubbleSort(new int[] { -3, -9, -2, -1 }); } public static void bubbleSort(int[] numbers) { System.out.printf("Unsorted array in Java :%s %n", Arrays.toString(numbers)); for (int i = 0; i < numbers.length; i++) { for (int j = numbers.length -1; j > i; j--) { if (numbers[j] < numbers[j - 1]) { swap(numbers, j, j-1); } } } System.out.printf("Sorted Array using Bubble sort algorithm :%s %n", Arrays.toString(numbers)); } public static void swap(int[] array, int from, int to){ int temp = array[from]; array[from] = array[to]; array[to] = temp; } }
Output:
Unsorted array in Java : [20, 12, 45, 19, 91, 55]
Sorted Array using Bubble sort algorithm : [12, 19, 20, 45, 55, 91]
Unsorted array in Java : [-1, 0, 1]
Sorted Array using Bubble sort algorithm : [-1, 0, 1]
Unsorted array in Java : [-3, -9, -2, -1]
Sorted Array using Bubble sort algorithm : [-9, -3, -2, -1]