Untitled
unknown
java
a year ago
2.2 kB
64
Indexable
Never
import java.util.Arrays; import java.util.Random; import java.util.Scanner; /** * This program allows users to input the number of elements in an array, * generates random integers within a specified range for each element, * and then displays the unsorted and sorted arrays using the bubble sort algorithm. */ public class P0001 { /** * The main method of the program. * * @param args command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Prompt the user to input the number of elements in the array System.out.print("Enter the number of elements in the array: "); int size = scanner.nextInt(); // Prompt the user to input the range of random numbers System.out.print("Enter the minimum value for random numbers: "); int min = scanner.nextInt(); System.out.print("Enter the maximum value for random numbers: "); int max = scanner.nextInt(); // Create the array and generate random integers within the specified range int[] array = new int[size]; Random random = new Random(); for (int i = 0; i < size; i++) { array[i] = random.nextInt(max - min + 1) + min; } // Display the unsorted array System.out.println("Unsorted Array: " + Arrays.toString(array)); // Sort the array using bubble sort bubbleSort(array); // Display the sorted array System.out.println("Sorted Array: " + Arrays.toString(array)); } /** * Sorts the given array in ascending order using the bubble sort algorithm. * * @param array the array to be sorted */ public static void bubbleSort(int[] array) { int n = array.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (array[j] > array[j + 1]) { // Swap array[j] and array[j+1] int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } }