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

Merge Sort

The document presents a Java program that implements the Merge Sort algorithm using a Divide & Conquer approach to sort elements in a list. It includes methods for merging sub-arrays and recursively sorting the array. The program also counts basic operations and generates random numbers for sorting.

Uploaded by

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

Merge Sort

The document presents a Java program that implements the Merge Sort algorithm using a Divide & Conquer approach to sort elements in a list. It includes methods for merging sub-arrays and recursively sorting the array. The program also counts basic operations and generates random numbers for sorting.

Uploaded by

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

Program-3:Design and implement a program in Java to sort the elements in a list by

breaking them into sub-lists using a Divide & Conquer- Recursive algorithm
implementation- Merge Sort.

import java.util.Scanner;
import java.util.Random;

public class MergeSort


{
public static int count=0;
static void merge(int a[], int low,int mid,int high)
{
int i=low,j=mid+1,k=0,c[];
//Create a temporary array C to size of the input array
c = new int[(high-low)+1];
while((i<=mid) && (j<=high))
{
count++;
//choose the least element and store in Temporary array 'C'
if(a[i]<a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
//COpy the remaining array elements from any one of sub-array
while(i<=mid)
c[k++]=a[i++];
while(j<=high)
c[k++]=a[j++];
for(i=low,j=0;j<k;i++,j++)
a[i]=c[j];

}
static void merge_sort(int a[],int low,int high)
{
int mid;
if(low < high)
{
//Divide the given array into 2 parts
mid=(low+high)/2;
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merge(a,low,mid,high);
}
}

public static void main(String args[])


{
int n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no. of elements");
n = s.nextInt();
int a[] = new int[n];
//use random class object to generate random values
Random r = new Random();
System.out.println("intput numbers");
for(int i=0;i<n;i++)
{
a[i]=r.nextInt(100);
System.out.print(a[i] + " ");
}

merge_sort(a,0, n-1);

System.out.println("Sorted numbers are");


for(int i=0;i<n;i++)
System.out.print(a[i] + " ");
System.out.println("No. of Basic operations: " + count);
}
}

You might also like