1 Write a computer program in JAVA that prompts the user for
1. Write a computer program in JAVA that prompts the user for a number, creates an array for that number of random integers, and then uses the bubble sort to order the array. The program should print out the array prior to the call to the sorting algorithm and afterwards.
2. Repeat 1 but use selection sort this time.
Solution
Hi, I have implemented all methods.
I have also tested first one(bubble sort).
Please let me know in case of any issue.
import java.util.Random;
import java.util.Scanner;
public class BubbleSort {
// bubble sort
public static void bubbleSort(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
}
}
// selection sort
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
private static void printArray(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + \" \");
}
System.out.println();
}
public static void main(String[] args) {
// Scanner Object to take user inut
Scanner sc = new Scanner(System.in);
System.out.print(\"How many number tou want to generate ? \");
int n = sc.nextInt();
// creating an integer arrray of size n
int arr[] = new int[n];
// Random number Object
Random random = new Random();
// filling array with random numbers in range 1-100
for(int i=0; i<n; i++){
arr[i] = random.nextInt(100)+1; // in range 1-100
}
// calling print method
printArray(arr);
// calling bubble sort methods
bubbleSort(arr);
// calling print method
printArray(arr);
}
}
/*
Sample run:
How many number tou want to generate ? 10
1 41 80 24 2 35 51 33 45 57
1 2 24 33 35 41 45 51 57 80
*/



