In this problem, you will write an implementation of BubbleSort. Your function should take in a single line representing an array of integers, and output a single line containing the list in
ascending order.
For example, if you receive the following input followed by a newline:
8 7 6 5 4 3 2 1
then you should display the following output followed by a newline:
1 2 3 4 5 6 7 8
Starter code for reading the input and writing the output has been written for you. Your job is to implement the bubbleSort() function.
Any code that does not explicitly implement the BubbleSort algorithm will receive a score of zero. Additionally, you must implement an algorithm with worst-case running time in O(n^2), best-case running time in Ω(n), and space usage in Θ(1) to receive full credit for design.
//Starter code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read in the list of numbers
int[] numbers;
String input = sc.nextLine();
if (input.equals("")) {
numbers = new int[0];
} else {
String[] numberStrings = input.split(" ");
numbers = new int[numberStrings.length];
for (int i = 0; i < numberStrings.length; i++) {
numbers[i] = Integer.parseInt(numberStrings[i]);
}
}
// Sort the list
bubbleSort(numbers);
// Print the sorted list
StringBuilder resultSb = new StringBuilder();
for (int i = 0; i < numbers.length; i++) {
resultSb.append(new Integer(numbers[i]).toString());
if (i < numbers.length - 1) {
resultSb.append(" ");
}
}
System.out.println(resultSb.toString());
}
public static void bubbleSort(int[] numbers) {
// TODO implement this function
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Read in the list of numbers int[] numbers; String input = sc.nextLine(); if (input.equals("")) { numbers = new int[0]; } else { String[] numberStrings = input.split(" "); numbers = new int[numberStrings.length]; for (int i = 0; i < numberStrings.length; i++) { numbers[i] = Integer.parseInt(numberStrings[i]); } } // Sort the list bubbleSort(numbers); // Print the sorted list StringBuilder resultSb = new StringBuilder(); for (int i = 0; i < numbers.length; i++) { resultSb.append(new Integer(numbers[i]).toString()); if (i < numbers.length - 1) { resultSb.append(" "); } } System.out.println(resultSb.toString()); } public static void bubbleSort(int[] numbers) { int temp; for (int i = 0; i < numbers.length - 1; i++) { for (int j = 0; j < numbers.length - 1; j++) { if (numbers[j] > numbers[j + 1]) { temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } } }
Get Answers For Free
Most questions answered within 1 hours.