0% found this document useful (0 votes)
4 views1 page

Java Merge Sort Implementation

The document presents a Java implementation of the Merge Sort algorithm. It includes a 'merge' method that combines two sorted subarrays and a 'mergeSort' method that recursively divides the array into smaller sections. The code effectively sorts an array in ascending order using the divide-and-conquer approach.

Uploaded by

Miab
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)
4 views1 page

Java Merge Sort Implementation

The document presents a Java implementation of the Merge Sort algorithm. It includes a 'merge' method that combines two sorted subarrays and a 'mergeSort' method that recursively divides the array into smaller sections. The code effectively sorts an array in ascending order using the divide-and-conquer approach.

Uploaded by

Miab
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

Lecture Data Structure (Java): Merge Sort

public class MergeSort {


public void merge(int[] a, int leftFront, int leftLast, int rightFront, int rightLast){
int[] tempList = new int[[Link]];
int i = leftFront;
int saveLeftFirst = leftFront;
while(leftFront <= leftLast && rightFront <= rightLast){
if(a[leftFront] > a[rightFront]){
tempList[i] = a[leftFront];
leftFront++;
}
else{
tempList[i] = a[rightFront];
rightFront++;
}
i++;
}
while(leftFront <= leftLast){
tempList[i] = a[leftFront];
leftFront++;
i++;
}
while(rightFront <= rightLast){
tempList[i] = a[rightFront];
rightFront++;
i++;
}
for(i = saveLeftFirst; i < rightFront; i++)
a[i] = tempList[i];
}

public void mergeSort(int[] a, int first, int last){


int middle;
if(first < last){
middle = (first + last) / 2;
mergeSort(a, first, middle);
mergeSort(a, middle + 1, last);
merge(a, first, middle, middle + 1, last);
}
}
}

You might also like