Write a class named BubbleSort with the following methods and functionality: Wri
ID: 3860161 • Letter: W
Question
Write a class named BubbleSort with the following methods and functionality: Write a bubbleSort method that implements a sort method that uses the bubble-sort algorithm. Your source in this method must use at least one (1) while loop. public static int[] bubbleSort(int[] array) Write a main method that: Prompts the user to enter 10 integers Calls the bubbleSort method, passing it the 10 integer array. Retrieves the sorted array from bubbleSort and displays the array to the screen.
Hint: The bubble-sort algorithm makes several passes through the array. On each pass, successive neighboring pairs are compared. If a pair is in decreasing order, its values are swapped; otherwise, the values remain unchanged. The technique is called a bubble sort or sinking sort because the smaller values gradually “bubble” their way to the top and the larger values “sink” to the bottom.
Here’s a sample run: Enter 10 integer values: 54 92 4 59 72 68 40 64 63 7 Bubble-sorted array: 4 7 40 54 59 63 64 68 72 92
Explanation / Answer
BubbleSort.java
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
int array[] = new int[10];
Scanner scan = new Scanner(System.in);
System.out.println("Enter 10 integer values: ");
for(int i=0;i<array.length;i++){
array[i]=scan.nextInt();
}
bubbleSort(array);
System.out.println("Bubble-sorted array:");
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void bubbleSort(int[] array) {
int n = array.length;
int temp;
for(int i=0; i < n; i++){
int j=1;
while(j < (n-i)){
if(array[j-1] > array[j]){
//swap the elements!
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
j++;
}
}
}
}
Output:
Enter 10 integer values:
54 92 4 59 72 68 40 64 63 7
Bubble-sorted array:
4 7 40 54 59 63 64 68 72 92
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.