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

Merge Sort

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)
28 views1 page

Merge Sort

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
You are on page 1/ 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