This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
RE:Sort order
Posted by Kishori Sharan on August 08, 2000 at 2:14 PM
Hi In merge( int, int, int ) method the following line of code does the actual sorting. this.compareElementsAt(secondHalf, firstHalf) < 0 So it is the compareElementsAt () method's return value that dictates how to sort the array. If you change < 0 to > 0 that should work. But, But the actual comparision for array elements will go in the compareElementAt () method and the return value will decide how to sort. I have given an example with Integer array just to show how it will work at run time. Thanx Kishori //////////// Example with your original code
abstract class MergeSort extends Object { protected Object toSort[]; protected Object swapSpace[]; public void sort(Object array[]) { if( array != null && array.length > 1 ) { int maxLength; maxLength = array.length; swapSpace = new Object[maxLength]; toSort = array; this.mergeSort(0, maxLength - 1); swapSpace = null; toSort = null; } } public abstract int compareElementsAt(int beginLoc, int endLoc); protected void mergeSort(int begin, int end) { if(begin != end) { int mid; mid = (begin + end) / 2; this.mergeSort(begin, mid); this.mergeSort(mid + 1, end); this.merge(begin, mid, end); } } protected void merge(int begin, int middle, int end) { int firstHalf, secondHalf, count; firstHalf = count = begin; secondHalf = middle + 1; while((firstHalf <= middle) && (secondHalf <= end)) { if(this.compareElementsAt(secondHalf, firstHalf) < 0) swapSpace[count++] = toSort[secondHalf++]; else swapSpace[count++] = toSort[firstHalf++]; } if(firstHalf <= middle) { while(firstHalf <= middle) swapSpace[count++] = toSort[firstHalf++]; } else { while(secondHalf <= end) swapSpace[count++] = toSort[secondHalf++]; } for(count = begin;count <= end;count++) toSort[count] = swapSpace[count]; } } public class KSort extends MergeSort { public int compareElementsAt(int beginLoc, int endLoc) { Integer a1, a2; a1 = ( Integer ) toSort[beginLoc] ; a2 = ( Integer ) toSort[endLoc] ; int v1, v2 ; v1 = a1.intValue ( ) ; v2 = a2.intValue ( ) ; // When you change the return value here // it will changet the sort criteria. Try // commenting following lines and uncommenting the commented ones if ( v1 > v2) return 1 ; else if ( v1 < v2 ) return -1 ; else return 0; /* if ( v1 > v2) return -1 ; else if ( v1 < v2 ) return 1 ; else return 0; */ } public static void main ( String[] args ) { Integer[] nums = new Integer[] { new Integer(10), new Integer(2), new Integer(30) } ; new KSort().sort ( nums ) ; for ( int i = 0; i < nums.length ; i++ ) System.out.println ( nums[i].intValue() ) ; } }
Replies:
|