跟着《Java数据结构和算法》学习到了快速排序,有个划分需要了解。
“划分数据就是把数据分为两组,使所有关键字大于特定值的数据项在一组,使所有关键字小于特定值的数据项在另一组。”
public class partition {
public static int part(int left, int right, int value, int[] array) {
if(left < 0 || right > array.length - 1) {
System.out.println("Invalid input.");
return -1;
}
int leftIndex = left - 1;
int rightIndex = right + 1;
while(true) {
while(leftIndex < rightIndex && array[++leftIndex] <= value) {}
while(rightIndex > leftIndex && array[--rightIndex] >= value) {}
if(leftIndex >= rightIndex) {
break;
}
int temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
return leftIndex;
}
public static void main(String[] args) {
int[] a = {11,33,44,99,88,55,66,22,77};
System.out.println(part(0,a.length - 1,33,a));
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}