In: Computer Science
Programming Language: JAVA
In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method.
Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers.
This can be done by looping until there are no more swaps being made, or using a nested for loop, meaning the array of length n is checked n2 times.
Sample Run #1
Please enter the # of numbers to be sorted: 4
Enter 1 for int's or 2 for doubles: 2
Enter number: 4
Enter number: 3
Enter number: 2
Enter number: 1
3.0, 4.0, 2.0, 1.0
3.0, 2.0, 4.0, 1.0
2.0, 3.0, 4.0, 1.0
2.0, 3.0, 1.0, 4.0
2.0, 1.0, 3.0, 4.0
1.0, 2.0, 3.0, 4.0
import java.util.Scanner;
public class TestBubbleSort {
public static void bubbleSort(int arr[]) {
int n = arr.length;
int i, j, temp;
// outer loop to travel through the
all elements
for (i = 0; i < n - 1; i++)
{
printArray(arr);
// inner loop to
compare the outer loop elements
for (j = 0; j
< n - i - 1; j++) {
// if element at j< than j+1 than swap
both
if (arr[j] > arr[j + 1]) {
// swap logic
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void bubbleSort(double arr[]) {
double n = arr.length;
int i, j;
double temp;
// outer loop to travel through the
all elements
for (i = 0; i < n - 1; i++)
{
// inner loop to
compare the outer loop elements
printArray(arr);
boolean swapped
= false;
for (j = 0; j
< n - i - 1; j++) {
// if element at j< than j+1 than swap
both
if (arr[j] > arr[j + 1]) {
// swap logic
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
private static void printArray(int[] arr) {
for (int i = 0; i < arr.length;
i++)
System.out.print(arr[i] + " ");
System.out.println();
}
private static void printArray(double[] arr)
{
for (int i = 0; i < arr.length;
i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter number of
elements: ");
int n = sc.nextInt();
System.out.println("Enter 1 for
int's or 2 for doubles: ");
int ch = sc.nextInt();
if (ch == 1) {
int arr[] = new
int[n];
for (int i = 0;
i < n; i++) {
System.out.println("Enter number: ");
arr[i] = sc.nextInt();
}
bubbleSort(arr);
printArray(arr);
} else {
double arr[] =
new double[n];
for (int i = 0;
i < n; i++) {
System.out.println("Enter number: ");
arr[i] = sc.nextDouble();
}
bubbleSort(arr);
printArray(arr);
}
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me