Implementing Bubble Sort

To implement bubble sort in Java, follow these steps:

  1. Apply the pseudocode shown in Snippet 2.1 in Java. Create a class and a method, accepting an array to sort as follows:
 public void sort(int[] numbers) 
  1. The slightly tricky part of this algorithm is the swapping logic. This is done by assigning one of the elements to be swapped to a temporary variable, as shown in Snippet 2.2:
public void sort(int[] numbers) {
for (int i = 1; i < numbers.length; i++) {
for (int j = 0; j < numbers.length - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
Snippet 2.2: Bubble sort solution. Source class name: BubbleSort

Go to
https://goo.gl/7atHVR to access the code.

Although bubble sort is very easy to implement, it's also one of the slowest sorting methods out there. In the next section, we will look at how we can slightly improve the performance of this algorithm.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.115