您的位置:首页 > 其它

高级排序-快速排序,最右边的值为枢纽

2017-02-23 12:33 302 查看
package g_advancedSort.C_quickSort;

/**

 * 快速排序,最右边的值为枢纽

 * @author Administrator

 *

 */

public class QuickSortApp {
public static void main(String[] args) {
int maxSize = 10;
ArrayIns arr = new ArrayIns(maxSize);
for (int i = 0; i < maxSize; i++) {
long n = (int) (Math.random() * 99);
arr.insert(n);
}
arr.display();
arr.quickSort();
arr.display();
}

}package g_advancedSort.C_quickSort;

public class ArrayIns {
private long[] theArray;
private int nElems;

public ArrayIns(int max) {
theArray = new long[max];
nElems = 0;
}

public void insert(long value) {
theArray[nElems++] = value;
}

public void display() {
System.out.println("A = ");
for (int i = 0; i < nElems; i++) {
System.out.print(theArray[i] + " ");
}
System.out.println();
}

public void quickSort() {
recQuickSort(0, nElems - 1);
}

/*
* 快速排序
*/
private void recQuickSort(int left, int right) {
if (right - left <= 0) {
return;
} else {
long pivot = theArray[right];

int partition = parttitionIt(left, right, pivot);
recQuickSort(left, partition - 1);
recQuickSort(partition + 1, right);

}
}

/*
* 划分
*/
private int parttitionIt(int left, int right, long pivot) {
int leftPtr = left - 1;
int rightPtr = right;
while (true) {
while (theArray[++leftPtr] < pivot)//leftPtr-1划分数组之外
;
while (rightPtr > 0 && theArray[--rightPtr] > pivot)//right划分子数组之外
;
if (leftPtr >= rightPtr)//2种情况,最大和最小值时停止
break;
else
swap(leftPtr, rightPtr);
}
swap(leftPtr, right);
return leftPtr;
}

/*
* 交换
*/
public void swap(int dex1, int dex2) {
long temp = theArray[dex1];
theArray[dex1] = theArray[dex2];
theArray[dex2] = temp;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: