Question

In: Computer Science

IN JAVA write a program that asks a user for a maximum of 20 user-inputted elements...

IN JAVA

write a program that asks a user for a maximum of 20 user-inputted elements and create an array. Then, write a Merge Sort function with recursion (in the main) that takes the user inputted elements in the array, sorts them, and prints them back.

Solutions

Expert Solution

The following is the program that allows user to input upto 20 elements and get it merge sorted. The program is commented side by side to the code for better understanding.

import java.util.Scanner;

public class HelloWorld{
    // Merge function that merges two sorted arrays.
    // Time complexity : O(N)
    // Space complexity: O(N)
    static void merge(int[] arr, int l, int m, int r)
    {
        // Create an array to hold elements that are inserted while
        // sorting in merge.
        int mergeOut[] = new int[r-l+1];
        int i=l, j=m+1; //Seggregate input array into left and right parts.
        int x = 0; // Pointer to start of output array.
        for(; i<=m && j<=r;){
          // Adds elements from left/right part based on which is smaller
          // in the given instant. Smaller one of the left and right side
          // is added and the pointer is incremented.
            if(arr[i]<arr[j]){
                mergeOut[x++] = arr[i++];
            } else {
                mergeOut[x++] = arr[j++];
            }
        }
        // Adds remaining elements in left side.
        while(i<=m){
            mergeOut[x++] = arr[i++];
        }
        // Adds remaining elements in right side.
        while(j<=r){
            mergeOut[x++] = arr[j++];
        }
        // Copies output array to input array.
        for(j=l, i=0; j<=r; i++, j++){
            arr[j] = mergeOut[i];
        }
    }
    // MergeSort: Divide and Conquer Algorithm
    // Time complexity : O(NLogN)
    // Space Complexity : O(N)
    static void mergeSort(int[] arr, int l, int r)
    {
        if (l < r)
        {
            int m = l+(r-l)/2;
            mergeSort(arr, l, m);
            mergeSort(arr, m+1, r);
            merge(arr, l, m, r);
        }
    }
    // Prints resultant array.
    // Time complexity : O(N)
    // Space complexity : O(1)
    static void printArray(int[] arrayEl){
        System.out.println("Sorted Array: ");
        for(int i=0; i<arrayEl.length; i++){
            System.out.print(arrayEl[i]+" ");
        }
        System.out.println("");
    }
    public static void main(String []args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of elements to be sorted");
        int elementCount = scanner.nextInt();
        if(elementCount>20){
            System.out.println("ERROR!! Enter less than 20 elements");
            return;
        }
        int arrayEl[] = new int[elementCount];
        System.out.println("Enter elements to be sorted");
        for(int i=0; i<arrayEl.length; i++){
            int temp = scanner.nextInt();
            System.out.println("Input element: " + temp);
            arrayEl[i] = temp;
        }
        mergeSort(arrayEl, 0, elementCount-1);
        printArray(arrayEl);
     }
}


Related Solutions

Write a program IN JAVA that asks the user for a number. The program should check...
Write a program IN JAVA that asks the user for a number. The program should check the number to ensure that it is valid (if not, the user should enter a valid number to continue.) The program should print out all of the prime numbers from 2 up to the number, with up to 10 numbers per line. (Recall: A prime number is a number that is only divisible by itself and 1.) The code should ask the user if...
Program should be written in Java a) Write a program that asks the user to enter...
Program should be written in Java a) Write a program that asks the user to enter the approximate current population of India. You should have the computer output a prompt and then YOU (as the user should enter the population.)  For testing purposes you may use the value of 1,382,000,000 from August 2020. Assume that the growth rate is 1.1% per year. Predict and print the predicted population for 2021 and 2022. The printout should include the year and the estimated...
Write a Java program that asks the user to enter an integer that is used to...
Write a Java program that asks the user to enter an integer that is used to set a limit that will generate the following four patterns of multiples of five using nested loops •Ascending multiples of five with ascending length triangle •Ascending multiples of five with descending length (inverted) triangle •Descending multiples of five with ascending length triangle •Descending multiples of five with descending length (inverted) triangle Use error checking to keep asking the user for a positive number until...
Write a java program that asks the user for a number n and gives them the...
Write a java program that asks the user for a number n and gives them the possibility to choose between computing the sum and computing the product of 1,…,n. Example of running this program: Enter an integer number n: __7________ Enter Sum or Product: __Sum__________________________________ Program output: Sum of 1 ... 7 Sum or Product: Sum Sum = 28 Now second sample of second execution Enter an integer number n: __5__________________________________ Enter Sum or Product: __Product__________________________________ Program output:  Product of 1...
Write a program in Java that first asks the user to type in today's price of...
Write a program in Java that first asks the user to type in today's price of one dollar in Japanese yen, then reads U.S. dollar values and converts each to yen. Use 0 as a sentinel to denote the end of dollar input. THEN the program reads a sequence of yen amounts and converts them to dollars. The second sequence is terminated by another zero value.
Time Calculator – Intro To Programming - JAVA Write a program that asks the user to...
Time Calculator – Intro To Programming - JAVA Write a program that asks the user to enter a number of seconds. • There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds. • There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to...
Java Program 1. Write a program that asks the user: “Please enter a number (0 to...
Java Program 1. Write a program that asks the user: “Please enter a number (0 to exit)”. Your program shall accept integers from the user (positive or negative), however, if the user enters 0 then your program shall terminate immediately. After the loop is terminated, return the total sum of all the previous numbers the user entered. a. What is considered to be the body of the loop? b. What is considered the control variable? c. What is considered to...
Using a while loop. Write a JAVA program that asks a user for an integer between...
Using a while loop. Write a JAVA program that asks a user for an integer between 1 and 9. Using the user input, print out the Fibonaccci series that contains that number of terms. Sample output: How many terms would like printed out for the Fibonacci Sequence? 7 Fibonacci Series of 7 numbers: 0 1 1 2 3 5 8
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to...
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to enter two strings. First, the program prompts: Please enter a string. The program should read in the string, and prompts: Please enter another string. The program reads in two strings and it prints a menu to the user. The program asks for user to enter an option and performs one of the following: Here are the options on the menu: Option a: checks if...
Instructions Write a Java program that asks the user t enter five test scores. The program...
Instructions Write a Java program that asks the user t enter five test scores. The program should display a letter grade for each score and the average test score. Write the following methods in the program: * calcAverage -- This method should accept five test scores as arguments and return the average of the scores. * determineGrade -- This method should accept a test score as an argument and return a letter grade for the score, based on the following...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT