目标:在一组数a0,a1,a2,a3,a4,a5,a6,a7,a8,a9中尽量取其中间值,以此为pivot,值大于pivot的元素置于pivot左边,反之至于右边。
源代码:
package com.paixu;
public class ArrayPar {
private int nElems; private long[] arr; public ArrayPar(int max){ arr = new long[max]; nElems =0; } public void insert(long value){ arr[nElems++] = value; } public void display(){ for(int i=0;i<nElems;i++) System.out.print("the" + i + "Elem is " + arr[i] + " " ); } public int size(){ return nElems; } public int partitionIt(int left,int right,int pivot){ int leftPtr = left -1; int rightPtr = right + 1; while(true){ while(leftPtr < right && arr[++leftPtr] < pivot) ; while(rightPtr > left && arr[--rightPtr] > pivot) ; if(leftPtr >= rightPtr) break; else swap(leftPtr,rightPtr); } return leftPtr; } public void swap(int leftValue,int rightValue){ long temp; temp =arr[rightValue]; arr[rightValue] = arr[leftValue]; arr[leftValue] = temp; }}
package com.paixu;
public class PartitionApp {
public static void main(String[] args){
int maxSize = 20; ArrayPar arr = new ArrayPar(maxSize); for(int i=0;i<maxSize;i++){ long n = (long)(Math.random() * 99); arr.insert(n); } arr.display(); System.out.println(); int pivor = 50; int size = arr.size(); int partDex = arr.partitionIt(0, size-1, pivor); System.out.println("Partition is at index " + partDex); arr.display(); }}