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

Java Merge Sort Implementation

The document contains a Java class that implements the merge sort algorithm. It includes methods for sorting an array and printing the sorted array. The main method demonstrates sorting a sample array and printing the result.

Uploaded by

rahulsuthrapu616
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)
3 views2 pages

Java Merge Sort Implementation

The document contains a Java class that implements the merge sort algorithm. It includes methods for sorting an array and printing the sorted array. The main method demonstrates sorting a sample array and printing the result.

Uploaded by

rahulsuthrapu616
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

public class D_A_CQ {

public static void printArray(int arr[]){


for(int i=0;i<=[Link]-1;i++){
[Link](arr[i]+" ");
}
[Link]();
}

//mergeSort
static void mergeSort(int arr[],int si,int ei){

if(si>=ei){
return;
}
int mid = si+(ei-si)/2;
mergeSort(arr, si, mid); //left sort
mergeSort(arr, mid+1, ei); //right sort
merge(arr,si,mid,ei);
}
public static void merge(int arr[],int si,int mid,int ei){
int temp []=new int[ei-si+1];
int i=si; //index for left sorted array
int j=mid+1; //index for right sorted array
int k=0; //index for temp[]

while(i<=mid && j<=ei){


if(arr[i]<arr[j]){
temp[k]=arr[i];
i++; k++;
}else{
temp[k]=arr[j];
k++; j++;
}
}

//for leftover elements in left sorted part

while(i<=mid){
temp[k++]=arr[i++];
}

//for leftover elements in right sorted part

while(j<=ei){
temp[k++]=arr[j++];
}

//copy temp[] to original arr[]


for(k=0 ,i=si;k<[Link];k++, i++){
arr[i]=temp[k];
}

public static void main(String[] args) {


int arr[]={6,3,9,5,2,8};
mergeSort(arr, 0, [Link]-1);
printArray(arr);

You might also like