156k views
2 votes
Write a program that reads in 10 numbers from the user and stores them in a 1D array of size 10. Then, write BubbleSort to sort that array – continuously pushing the largest elements to the right side

1 Answer

6 votes

Answer:

The solution is provided in the explanation section.

Detailed explanation is provided using comments within the code

Step-by-step explanation:

import java.util.*;

public class Main {

//The Bubble sort method

public static void bb_Sort(int[] arr) {

int n = 10; //Length of array

int temp = 0; // create a temporal variable

for(int i=0; i < n; i++){

for(int j=1; j < (n-i); j++){

if(arr[j-1] > arr[j]){

// The bubble sort algorithm swaps elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

}

}

}

}

public static void main(String[] args) {

//declaring the array of integers

int [] array = new int[10];

//Prompt user to add elements into the array

Scanner in = new Scanner(System.in);

//Use for loop to receive all 10 elements

for(int i = 0; i<array.length; i++){

System.out.println("Enter the next array Element");

array[i] = in.nextInt();

}

//Print the array elements before bubble sort

System.out.println("The Array before bubble sort");

System.out.println(Arrays.toString(array));

//Call bubble sort method

bb_Sort(array);

System.out.println("Array After Bubble Sort");

System.out.println(Arrays.toString(array));

}

}

User Pa
by
5.4k points