j 2 meソートメソッド整数配列

2114 ワード


package xxx.yyy.zzz.tst;

import java.util.Random;

public class MySortMethodTst {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int[] array = new int[100];
		Random random = new Random();

		/* load some random values into the array */
		for (int i = 0; i < 100; i++) {
			array[i] = random.nextInt() % 100;
		}

		/* print the original array */
		System.out.println("===***=== Before sorting: ");
		for (int i = 0; i < array.length; i++) {
			System.out.printf(" %d ", array[i]);
		}
		System.out.println();

		// use mySortMethod
		mySortMethod(array, 0, array.length - 1);

		System.out.println("===***=== After sorting: ");
		for (int i = 0; i < array.length; i++) {
			System.out.printf(" %d ", array[i]);
		}
		System.out.println();

	}

	/* sort everything in between lowIndex and highIndex */
	private static void mySortMethod(int[] arrayToSort, int lowIndex,
			int highIndex) {
		int i = lowIndex;
		int j = highIndex;
		int y = 0;
		/* compare value */
		int z = arrayToSort[(lowIndex + highIndex) / 2];

		/* partition */
		do {
			/* find member above ... */
			while (arrayToSort[i] < z)
				i++;

			/* find element below ... */
			while (arrayToSort[j] > z)
				j--;

			if (i <= j) {
				/* swap two elements */
				y = arrayToSort[i];
				arrayToSort[i] = arrayToSort[j];
				arrayToSort[j] = y;
				i++;
				j--;
			}
		} while (i <= j);

		/* recurse */
		if (lowIndex < j)
			mySortMethod(arrayToSort, lowIndex, j);

		if (i < highIndex)
			mySortMethod(arrayToSort, i, highIndex);
	}

}

j 2 meのapiが提供する方法は非常に限られており、普段よく使われている方法の多くはなく、すべて自分で書き直す必要があり、毎回方法を考えるのがおっくうで、コピーを書いてコピーしましょう.