Hi All,
Here I write a program for Merge Sort using java
Merge sort or merge sort is a simple but efficient sort algorithm that splits the list into two sub lists, sorts each one, then combines them into a single sorted list. It has good worst-case performance and requires only sequential access, making it ideal for sequential data structures like linked lists.
package Sorting;
import java.util.Scanner;
/* sort method */
public class MergeSort1 {
static void MergeMethod(int a[], int b) {
int sub[] = new int[25];
int i, j, k, lev1, lev2, lev3, u2, size;
size = 1;
while (size < b) { // check the array size
lev1 = 0;
k = 0;
while ((lev1 + size) < b) {
lev2 = lev1 + size;
lev3 = lev2 - 1;
u2 = ((lev2 + size - 1) < b) ? (lev2 + size - 1) : (b - 1);
for (i = lev1, j = lev2; i <= lev3 && j <= u2; k++) {
if (a[i] <= a[j]) {
sub[k] = a[i++];
} else {
sub[k] = a[j++];
}
}
for (; i <= lev3; k++) {
sub[k] = a[i++];
}
for (; j <= u2; k++) {
sub[k] = a[j++];
}
lev1 = u2 + 1;
}
for (i = lev1; k < b; i++) {
sub[k++] = a[i];
}
for (i = 0; i < b; i++) {
a[i] = sub[i];
}
size *= 2;
}
}
public static void main(String args[]) {
int i, n;
/* Getting value from user */
Scanner in = new Scanner(System.in);
System.out.print("Please Enter how many numbers to be sorted : \t");
n=new Scanner(System.in).nextInt();
System.out.println("\nEnter the numbers\n");
int x[] = new int[n];
for (i = 0; i < n; i++) {
x[i] = in.nextInt();
}
MergeMethod(x, n);
/* print out put of array*/
System.out.println("\nSorted Elements are :");
for (i = 0; i < n; i++) {
System.out.print(x[i] + " ");
}
}
}
OUTPUT:
~~~~~~~~
Please Enter how many numbers to be sorted : 8
Enter the numbers
5
60
2
1
95
25
35
3
Sorted Elements are :
1 2 3 5 25 35 60 95
Enter the numbers
5
60
2
1
95
25
35
3
Sorted Elements are :
1 2 3 5 25 35 60 95
No comments:
Post a Comment