SlideShare a Scribd company logo
Merge Sort java with a few details, please include comments if possible Generate an array with
100 random integers between 0 and 1000 Print the original array to the screen Use your merge
sort algorithm to sort the array from lowest to highest Print the sorted array to the screen
Solution
/* Class name MergeSortRandomNumber.java */
import java.util.Random;
public class MergeSortRandomNumber{
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String[] args) {
int inputArr[] =new int[10];// Storing array elements default 10 we can modify depends on
requirement
Random r = new Random();//Create Object for Random Predefined class
System.out.println("Random Numbers");//Printing Random Numbers
for(int i=0;i<10;i++)
{
int Low = 0;//Start from 0
int High = 100;//Up to 100
int Result = r.nextInt(High-Low) + Low;
System.out.print(Result);//Prining on the console random numbers
System.out.print(" ");
inputArr[i]=Result;
}
System.out.println("");
System.out.println("Input Array");//Printing input array on the console start
for(int i=0;i<10;i++)
{
System.out.print(inputArr[i]);//
System.out.print(" ");
} //Printing input array on the console end
System.out.println("");
System.out.println("After Merge sort from low to high");
//merge Sort Main logic started
RandomNumber mms = new RandomNumber();
mms.sort(inputArr);//Passing our input array calling sort() method
for(int i:inputArr){
System.out.print(i);//printing Final values from low to high
System.out.print(" ");
}
}
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);//Calling Merge sort main logic
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
//Compare elements at First and Second,
//and move smaller element at Merged array
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
=============================
Expected Out put
Random Numbers
19 95 97 32 86 36 48 34 46 71
Input Array
19 95 97 32 86 36 48 34 46 71
After Merge sort from low to high
19 32 34 36 46 48 71 86 95 97

More Related Content

PDF
Write a program that obtains the execution time of selection sort, bu.pdf
DOCX
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
DOCX
Write a program that will test a name) method no sorting routine from.docx
PDF
Write a method called uniqueNumbers that takes an int array as param.pdf
PDF
Describe a data structure that supports both removeMin() and rem.pdf
PPTX
Arrays in Java with example and types of array.pptx
PDF
Simple 27 Java Program on basic java syntax
DOCX
Example of JAVA Program
Write a program that obtains the execution time of selection sort, bu.pdf
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Write a program that will test a name) method no sorting routine from.docx
Write a method called uniqueNumbers that takes an int array as param.pdf
Describe a data structure that supports both removeMin() and rem.pdf
Arrays in Java with example and types of array.pptx
Simple 27 Java Program on basic java syntax
Example of JAVA Program

Similar to Merge Sort java with a few details, please include comments if possi.pdf (17)

PDF
Write a java program to randomly generate the following sets of data.pdf
PDF
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
PDF
I need help with the 2nd TODO comment and the other comments Ill.pdf
PDF
ReversePoem.java ---------------------------------- public cl.pdf
DOCX
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PDF
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
PPTX
6_Array.pptx
PPTX
Chap1 array
PDF
Simple Java Program for beginner with easy method.pdf
TXT
DOCX
QA Auotmation Java programs,theory
PDF
Here is what I got so far, I dont know how to write union, interse.pdf
PDF
SlideSet_4_Arraysnew.pdf
PDF
Below is the assignment description and the file I have written..pdf
PDF
C++ Nested loops, matrix and fuctions.pdf
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
DOCX
Required to augment the authors Binary Search Tree (BST) code to .docx
Write a java program to randomly generate the following sets of data.pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
I need help with the 2nd TODO comment and the other comments Ill.pdf
ReversePoem.java ---------------------------------- public cl.pdf
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
6_Array.pptx
Chap1 array
Simple Java Program for beginner with easy method.pdf
QA Auotmation Java programs,theory
Here is what I got so far, I dont know how to write union, interse.pdf
SlideSet_4_Arraysnew.pdf
Below is the assignment description and the file I have written..pdf
C++ Nested loops, matrix and fuctions.pdf
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Required to augment the authors Binary Search Tree (BST) code to .docx
Ad

More from feelinggifts (20)

PDF
Chapter 22. Problem 3BCP0 Bookmark Show all steps ON Problem Eminent.pdf
PDF
D Question 11 1 pts A fundamental feature of money that BitCoin fulfi.pdf
PDF
connect instructions I helg dule 7 Connect seve & Exit ..pdf
PDF
COMPUTER ETHICSDiscuss the local and global impact of malware and .pdf
PDF
You’re helping a group of ethnographers analyze some oral history da.pdf
PDF
A man with type B blood type claims to be biological father of a typ.pdf
PDF
why should filtrate be used to transfer the residue when the desired.pdf
PDF
Winch of the following is NOT one of the reasons an IO Exception is t.pdf
PDF
Why is attending to the full scope of drivers critical in implementi.pdf
PDF
Which of the following is not a function of interest groups A. to i.pdf
PDF
When explaining civil law one would say that it is concemed with disp.pdf
PDF
What is the difference between a short and long branchSolution.pdf
PDF
What is the maximum file size in a FAT32 systemSolutionFirst .pdf
PDF
View transaction list Journal entry worksheet The company paid $510 c.pdf
PDF
The numeric data types in C++ can be broken into two general categori.pdf
PDF
The capillaries at the alveoli Form a respiratory membrane Are spe.pdf
PDF
Select the word or phrase which best matches the description of it..pdf
PDF
Robin Hood has hired you as his new Strategic Consultant to help him.pdf
PDF
Research indicates that online news seekers tend to access topics of.pdf
PDF
Read Case Study Room 406 and answer the following questions in 2.pdf
Chapter 22. Problem 3BCP0 Bookmark Show all steps ON Problem Eminent.pdf
D Question 11 1 pts A fundamental feature of money that BitCoin fulfi.pdf
connect instructions I helg dule 7 Connect seve & Exit ..pdf
COMPUTER ETHICSDiscuss the local and global impact of malware and .pdf
You’re helping a group of ethnographers analyze some oral history da.pdf
A man with type B blood type claims to be biological father of a typ.pdf
why should filtrate be used to transfer the residue when the desired.pdf
Winch of the following is NOT one of the reasons an IO Exception is t.pdf
Why is attending to the full scope of drivers critical in implementi.pdf
Which of the following is not a function of interest groups A. to i.pdf
When explaining civil law one would say that it is concemed with disp.pdf
What is the difference between a short and long branchSolution.pdf
What is the maximum file size in a FAT32 systemSolutionFirst .pdf
View transaction list Journal entry worksheet The company paid $510 c.pdf
The numeric data types in C++ can be broken into two general categori.pdf
The capillaries at the alveoli Form a respiratory membrane Are spe.pdf
Select the word or phrase which best matches the description of it..pdf
Robin Hood has hired you as his new Strategic Consultant to help him.pdf
Research indicates that online news seekers tend to access topics of.pdf
Read Case Study Room 406 and answer the following questions in 2.pdf
Ad

Recently uploaded (20)

PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Presentation on HIE in infants and its manifestations
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
GDM (1) (1).pptx small presentation for students
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Computing-Curriculum for Schools in Ghana
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Pharma ospi slides which help in ospi learning
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
2.FourierTransform-ShortQuestionswithAnswers.pdf
Presentation on HIE in infants and its manifestations
A systematic review of self-coping strategies used by university students to ...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GDM (1) (1).pptx small presentation for students
102 student loan defaulters named and shamed – Is someone you know on the list?
Computing-Curriculum for Schools in Ghana
202450812 BayCHI UCSC-SV 20250812 v17.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Microbial disease of the cardiovascular and lymphatic systems
Pharma ospi slides which help in ospi learning
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
O5-L3 Freight Transport Ops (International) V1.pdf

Merge Sort java with a few details, please include comments if possi.pdf

  • 1. Merge Sort java with a few details, please include comments if possible Generate an array with 100 random integers between 0 and 1000 Print the original array to the screen Use your merge sort algorithm to sort the array from lowest to highest Print the sorted array to the screen Solution /* Class name MergeSortRandomNumber.java */ import java.util.Random; public class MergeSortRandomNumber{ private int[] array; private int[] tempMergArr; private int length; public static void main(String[] args) { int inputArr[] =new int[10];// Storing array elements default 10 we can modify depends on requirement Random r = new Random();//Create Object for Random Predefined class System.out.println("Random Numbers");//Printing Random Numbers for(int i=0;i<10;i++) { int Low = 0;//Start from 0 int High = 100;//Up to 100 int Result = r.nextInt(High-Low) + Low; System.out.print(Result);//Prining on the console random numbers System.out.print(" "); inputArr[i]=Result; } System.out.println(""); System.out.println("Input Array");//Printing input array on the console start for(int i=0;i<10;i++) { System.out.print(inputArr[i]);//
  • 2. System.out.print(" "); } //Printing input array on the console end System.out.println(""); System.out.println("After Merge sort from low to high"); //merge Sort Main logic started RandomNumber mms = new RandomNumber(); mms.sort(inputArr);//Passing our input array calling sort() method for(int i:inputArr){ System.out.print(i);//printing Final values from low to high System.out.print(" "); } } public void sort(int inputArr[]) { this.array = inputArr; this.length = inputArr.length; this.tempMergArr = new int[length]; doMergeSort(0, length - 1);//Calling Merge sort main logic } private void doMergeSort(int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; // Below step sorts the left side of the array doMergeSort(lowerIndex, middle); // Below step sorts the right side of the array doMergeSort(middle + 1, higherIndex); // Now merge both sides mergeParts(lowerIndex, middle, higherIndex); } }
  • 3. private void mergeParts(int lowerIndex, int middle, int higherIndex) { //Compare elements at First and Second, //and move smaller element at Merged array for (int i = lowerIndex; i <= higherIndex; i++) { tempMergArr[i] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (tempMergArr[i] <= tempMergArr[j]) { array[k] = tempMergArr[i]; i++; } else { array[k] = tempMergArr[j]; j++; } k++; } while (i <= middle) { array[k] = tempMergArr[i]; k++; i++; } } } ============================= Expected Out put Random Numbers 19 95 97 32 86 36 48 34 46 71 Input Array 19 95 97 32 86 36 48 34 46 71
  • 4. After Merge sort from low to high 19 32 34 36 46 48 71 86 95 97