Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

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[a.length];
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