Created
April 1, 2012 15:13
-
-
Save t-miya/2276201 to your computer and use it in GitHub Desktop.
クイックソートの勉強に組んでみました
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
/** | |
* クイックソートサンプル | |
*/ | |
public class QuickSortTest | |
{ | |
public static void main(String[] args) | |
{ | |
// ソート用の整数配列 | |
int[] array = createRundamIntArray(); | |
System.out.println("クイックソート前"); | |
arrayPrintln(array); | |
// クイックソート実行 | |
quickSort(array, 0, array.length-1); | |
System.out.println("クイックソート後"); | |
arrayPrintln(array); | |
} | |
/** | |
* ランダムな並びの配列を作成 | |
* @return | |
*/ | |
public static int[] createRundamIntArray() | |
{ | |
List<Integer> intList = new ArrayList<Integer>(); | |
for (int i=1; i<11; i++) | |
{ | |
intList.add(Integer.valueOf(i)); | |
} | |
// リストをシャッフル | |
Collections.shuffle(intList); | |
// 配列の組み直す | |
int[] array = new int[intList.size()]; | |
for (int i=0; i<intList.size(); i++) | |
{ | |
array[i] = intList.get(i); | |
} | |
return array; | |
} | |
/** | |
* クイックソートを行う | |
* @param array ソート対象配列 | |
* @param leftIndex 左開始点 | |
* @param rightIndex 右開始点 | |
*/ | |
public static void quickSort(int[] array, int leftIndex, int rightIndex) | |
{ | |
// 左開始点と右開始点がぶつかるまで行う | |
if(leftIndex <= rightIndex) | |
{ | |
// 軸要素を中間点にとる | |
int pivot = array[(leftIndex+rightIndex) / 2]; | |
int leftPos = leftIndex; | |
int rightPos = rightIndex; | |
while(leftIndex <= rightIndex) | |
{ | |
// 左から軸要素より大きい値を探していく | |
while(array[leftIndex] < pivot) | |
{ | |
leftIndex++; | |
} | |
// 右から軸要素より小さな値を探していく | |
while(array[rightIndex] > pivot) | |
{ | |
rightIndex--; | |
} | |
// ぶつかったら交換 | |
if(leftIndex <= rightIndex) | |
{ | |
int tmp = array[leftIndex]; | |
array[leftIndex] = array[rightIndex]; | |
array[rightIndex] = tmp; | |
// 交換したら探索続行 | |
leftIndex++; | |
rightIndex--; | |
} | |
} | |
// 軸要素より左側を再帰的にソート | |
quickSort(array, leftIndex, rightPos); | |
// 軸要素より右側を再帰的にソート | |
quickSort(array, leftPos, rightIndex); | |
} | |
} | |
/** | |
* 配列の値を標準出力 | |
* @param array 配列 | |
*/ | |
public static void arrayPrintln(int[] array) | |
{ | |
for(int i : array) | |
{ | |
System.out.println(String.valueOf(i) + " "); | |
} | |
System.out.println(""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Todo: ピボットの取り方とか、残り少なくなったら挿入ソートに移行とか。