Jump to content
  • Advertisement
Sign in to follow this  
masterLux

strange merge sort (NEED HELP)

This topic is 3165 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been working implementing mergeSort for class, but for some reason my code keeps outputting the input. I've been mining through the web looking for the right algorithm and I've used them all and the output remains the same. The output for this particular alg is the number of comparisons, but when I put it in a driver function and output the array, it comes out in the same order it came in, but number of comparisons > 0. My language is java. I understand that java uses pass-by-value, but I know that you can still manipulate objects and arrays because I tested it out before doing this alg. <code> import java.util.*; public class MergeSort { //total number of comparisons private int count; //l parameter is the left most index and r is the right more index public int mergeSort(int[] array, int l, int r) { int mid = (l+r)/2; if(l==r) { return 0; } mergeSort(array,l,mid); mergeSort(array,mid+1,r); return merge(array,l,mid+1,r); } private int merge(int[] array, int l, int m, int r) { //size of temp array int size = (r-l)+1; //temp array to contain ordered elements int tempArray[] = new int[size]; //mid value int mid = m-1; //temp array index int temp = 0; //puts both sides together while putting them in order while( (l <= mid) && (m <= r)) { if(array[l] <= array[m]) { tempArray[temp++]=array[l++]; count++; } else { tempArray[temp++] = array[m++]; count++; } } //copies over the rest of the array while(l <= mid) { tempArray[temp++] = array[l++]; } while(m <= r) { tempArray[temp++] = array[m++]; } for(int i = l; i <= r; i++) { System.out.print(tempArray[i-l]+" "); array = tempArray[i-l]; } System.out.println(); return count; } } </code>

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!