Ritu Singh
Summary:
We are given a random set of numbers with some ‘N’ numbers in it. Using java, we have to sort the numbers in ascending order and make a new array.
Solution:
Explanation:
This above code defines a class named Solution with two methods:
merge: This method takes two sorted arrays left and right as input and merges them into a single sorted array. It initialises an array result of size equal to the sum of the lengths of left and right. It then iterates through both arrays, comparing elements and placing them in the result array in sorted order. Finally, it returns the merged sorted array.
sortArr: This method takes an array arr and its length n as input and sorts the array using the merge sort algorithm. If the length of the array is less than or equal to 1, it returns the array as it is. Otherwise, it calculates the middle index mid of the array and creates two subarrays left and right by splitting the input array at the middle index. It recursively calls itself (sortArr) on both subarrays to sort them. Then, it merges the sorted left and right subarrays using the merge method and returns the merged sorted array.
In summary, this code implements the merge sort algorithm to sort an input array of integers. The merge method is responsible for merging two sorted arrays, while the sortArr method recursively applies the merge sort algorithm to sort the entire input array.
Suggested blogs:
>How to route between different components in React.js?
>How to save Python yaml and load a nested class?-Python
>How to send multiple HTML form fields to PHP arrays via Ajax?
>What is data binding in Angular?
>What is microservice architecture, and why is it better than monolithic architecture?
>What makes Python 'flow' with HTML nicely as compared to PHP?
>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?
>Creating custom required rule - Laravel validation