0% found this document useful (0 votes)
4 views3 pages

Lab Exam

The document contains a Java program that implements the Merge Sort algorithm. It prompts the user to input an array of integers, sorts the array using the merge sort technique, and prints the sorted array. The program includes methods for merging and sorting the array recursively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Lab Exam

The document contains a Java program that implements the Merge Sort algorithm. It prompts the user to input an array of integers, sorts the array using the merge sort technique, and prints the sorted array. The program includes methods for merging and sorting the array recursively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

import java.util.

Scanner;

public class Mergesort {

public static void main(String[] args) {

System.out.println("The Array that should be merge is :");

int[] num = new int[20];

Scanner input = new Scanner(System.in);

for (int i = 0; i < num.length; i++) {

System.out.print("Array : ");

num[i] = input.nextInt();

merge_Sort(num, 0, num.length - 1);

public static void merge_Sort(int num[], int left, int right) {

if (left < right) {

int m = left + (right - left) / 2;

merge_Sort(num, left, m);

merge_Sort(num, m + 1, right);

merge(num, left, m, right);

System.out.print("\n{");

for (int i = 0; i < num.length; i++) {

System.out.print(num[i] + ",");

System.out.print("}");

public static void merge(int num[], int l, int m, int r) {

int number1 = m - l + 1;

int number2 = r - m;
int left[] = new int[number1];

int right[] = new int[number2];

for (int i = 0; i < number1; ++i) {

left[i] = num[l + i];

for (int j = 0; j < number2; ++j) {

right[j] = num[m + 1 + j];

int i = 0, j = 0;

int k = l;

while (i < number1 && j < number2) {

if (right[j] > left[i]) {

num[k] = left[i];

i++;

} else {

num[k] = right[j];

j++;

k++;

while (i < number1) {

num[k] = left[i];

i++;

k++;

while (j < number2) {

num[k] = right[j];

j++;

k++;
}

You might also like