0% found this document useful (0 votes)
30 views2 pages

Package Import Public Class Public Static Void Int Int Int Int If Return Int

This Java code defines a class called Array that implements a merge sort algorithm. The sort method takes an integer array, lower and upper bounds, and recursively divides the array in half until arrays of size 1 are reached. It then merges the sorted subarrays back together into the original array. The main method gets user input to populate an array, calls the sort method, and prints the sorted results.

Uploaded by

Komal Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views2 pages

Package Import Public Class Public Static Void Int Int Int Int If Return Int

This Java code defines a class called Array that implements a merge sort algorithm. The sort method takes an integer array, lower and upper bounds, and recursively divides the array in half until arrays of size 1 are reached. It then merges the sorted subarrays back together into the original array. The main method gets user input to populate an array, calls the sort method, and prints the sorted results.

Uploaded by

Komal Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Array.

java

1 package MergeSort;
2 import java.util.*;
3
4 public class Array {
5
6 public static void sort(int[] x, int lower, int upper)
7 {
8 int num1 = upper - lower;
9 if(num1 <=1)
10 {
11 return;
12 }
13 int num2 = lower + num1/2;
14
15 sort(x, lower, num2);
16 sort(x, num2,upper);
17
18 int[] num3 = new int[num1];
19 int y = lower, z = num2;
20 for(int w = 0; w < num1; w++)
21 {
22 if(y == num2)
23 {
24 num3[w] = x[z++];
25 }
26 else if(z == upper)
27 {
28 num3[w] = x[y++];
29 }
30 else if(x[z] < x[y])
31 {
32 num3[w] = x[z++];
33 }
34 else
35 {
36 num3[w] = x[y++];
37 }
38 }
39 for(int w=0; w<num1; w++)
40 {
41 x[lower + w] = num3[w];
42 }
43 }
44
45 public static void main(String args[])
46 {
47 Scanner sc = new Scanner(System.in);
48 int num1, y;
49 System.out.println("Please choose number of array elements: ");
50 num1 = sc.nextInt();
51 int xyz[] = new int[num1];
52 System.out.println("Please insert " + num1 + " numbers of elements: ");
53 for(y=0; y<num1; y++)
54 {
55 xyz[y] = sc.nextInt();
56 }
57 sort(xyz, 0, num1);

Page 1
Array.java

58 System.out.println("Result of array after sorting: ");


59 for(y=0; y<num1; y++)
60 {
61 System.out.print(xyz[y] + " ");
62 }
63 System.out.println();
64 }
65 }
66

Page 2

You might also like