seacase 0 Newbie Poster

I seem to have hit a wall with implementing my own version of merge sort. I can sort the list fine in ascending order, but once I try to reverse the ordering (passing in a boolean), I get an ArrayIndexOutOfBounds error. I'm guessing that what I'm experiencing is some sort of one-off error?

Any suggestions? Where am I going wrong?

public void mergeSort(int[] array, int lowindex, int highindex,
			boolean reversed) {
		int[] temp = new int[array.length];
		mergeSort(array, temp, lowindex, highindex, reversed);
	}

	private static void mergeSort(int[] array, int[] temp, int low, int high,
			boolean reversed) {

		if (low >= high) {
			return;
		}
		
		int mid = (low + high) / 2;
		mergeSort(array, temp, low, mid, reversed);
		mergeSort(array, temp, mid + 1, high, reversed);
		merge(array, temp, low, mid, high, reversed);

	}

	private static void merge(int[] array, int[] temp, int low, int mid,
			int high, boolean reversed) {
		int insertindex = low;
		int lowindex = low;
		int highindex = mid + 1;

		while (insertindex <= high) {

			if (compare(mid, lowindex, reversed)) {
				temp[insertindex++] = array[highindex++];
			} else if (compare(high, highindex, reversed)) {
				temp[insertindex++] = array[lowindex++];
			} else if (compare(array[lowindex], array[highindex], reversed)) {
				temp[insertindex++] = array[lowindex++];
			} else {
				temp[insertindex++] = array[highindex++];
			}
		}
		for (insertindex = low; insertindex <= high; insertindex++) {
			array[insertindex] = temp[insertindex];
		}
	}
	public static boolean compare(int smaller, int larger, boolean reversed) {
		if (reversed) {
			if (smaller > larger) {
				return true;
			}
		} else {
			if (smaller < larger) {
				return true;
			}

		}
		return false;
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.