Question: In this exercise the goal is to implement the Bubble Sort algorithm on a small array. If you are comfortable with loops and arrays, you
In this exercise the goal is to implement the Bubble Sort algorithm on a small array. If you are comfortable with loops and arrays, you can solve this by implementing the full algorithms. If you are not, you can "unroll" the loop and implement each step by hand by hard coding each pass through the array as a sequence of explicit checks and potential swaps.
The skeleton contains two methods:
-
A main method which will allow you to do your own testing, and give a working example.
-
A bubbleSort method where you'll do the actual implementation of the sorting algorithm.
The bubbleSort method takes in an int[] called data. This is the array that you are to sort. You are guaranteed for this exercise that data will have length 4. At the end of the method you should return data;. This line has already been added, so you can just leave it as is.
For the tests to ensure you are correctly implementing a Bubble Sort (and not some other sort, or using a library), you must print out the array using printArray(data) every time you swap elements in the array. You should not print it out any other time in the bubbleSort method.
import java.util.Arrays;
public class BubbleSort {
//Don't touch this method! private static void printArray(int[] a) { System.out.println(Arrays.toString(a)); }
//Complete this method. public static int[] bubbleSort(int[] data) {
//Implement a Bubble Sort on data here!
return data; }
//You can mess around in the main method //as you wish. As long as it compiles, //it won't affect the testing. public static void main(String[] args) {
int[] testData = {45, 93, 33, 55};
System.out.println("Sorting."); testData = bubbleSort(testData); System.out.println("After sorting the array is: "); printArray(testData); }
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
