DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: How to make this sorting Algorithm work

#### Hybrid View

1. Registered User
Join Date
Aug 2008
Posts
1

## How to make this sorting Algorithm work

Hi, I'm pretty new to java and I'm trying to work on this sorting algorithm question.

here's the main bit:
Code:
```public static void chooseSongs(ArrayList<Song> l, int k)  {
int []tmpArray = new int[a.length];
mergeSort(a,tmpArray,0,a.length - 1);
}

private static void mergeSort(int[]a, int[]tmpArray, int left, int right) {
if( left < right) {
int centre = (left + right) /2;
mergeSort(a,tmpArray, left, centre);
mergeSort(a.tmpArray, centre + 1, right);
merge(a, tmpArray, left, centre + 1, right);
}
}

private static void merge(int[]a, int[]tmpArray, int leftPos, int rightPos, int rightEnd){
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int leftBeg = leftPos;

while(leftPos <= leftEnd && rightPos <= rightEnd){
if(a[leftPos] < a[rightPos]){
tmpArray[tmpPos++] = a[leftPos++];
}else{
tmpArray[tmpPos++] = a[rightPos++];
}
}

while(leftPos <= leftEnd){
tmpArray[tmpPos++] = a[leftPos++];
}

while(rightPos <= rightEnd){
tmpArray[tmpPos++] =a[rightPos++];
}

for(tmpPos = leftBeg; tmpPos <= rightEnd; tmpPos++){
a[tmpPos] = tmpArray{tmpPos};
}
}```
ummm it looks long and tedious but it's basically just the merge sort algorithm I've been given.

The code is using arraylist but to make it to work I'll have to change it toarrays. Because I'm a newbie and my java skill is poor I don't really know what to do. Any help would be great.

ps: I've attached the code for the whole thing if the above looks confusing (this application is suppose to sort a list of songname, artist and time into order)
Last edited by Hack; 08-14-2008 at 01:13 PM. Reason: Added Code Tags

2. Registered User
Join Date
Jul 2005
Location
SW MO, USA
Posts
299
Try debugging it by adding println() statements at key points and watch how control flows. use a short list of records to sort.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise