劃分算法

劃分算法的目的java

  咱們設定一個特定值,讓全部數據項大於特定值的在一組,小於特定值的在另外一組,劃分算法是快速排序的根本機制。算法

 

劃分算法的思想數組

  在數組的倆頭分別有倆個指針,倆個指針相向而行,假定咱們讓數組頭的部分爲小於特定值的數據項,數組尾的部分爲大於特定值的數據項,當指針相向移動的過程當中,頭指針遇到大於特定值的數據項而且尾指針也遇到小於特定值的數據項,則這倆個數據項交換位置,直到這倆個指針相遇,這時整個數組分爲倆個部分,數組前段爲小於特定值的數據項,數組後段爲大於特定值的數據項。dom

 

 

劃分算法的java程序spa

package sy;

class ArrayPar{
    private long[] theArray;
    private int nElems;
    
    public ArrayPar(int max){
        theArray = new long[max];
        nElems = 0;
    }
    
    public void insert(long value){
        theArray[nElems] = value;
        nElems ++;
    }
    
    public int size(){
        return nElems;
    }
    public void display(){
        System.out.print("A = ");
        for(int j = 0; j < nElems; j++)
        {
            System.out.print(theArray[j] + " ");
        }
        System.out.print("");
    }
    
    public int partitionIt(int left,int right,long value)
    {
        //定義左指針,由於內層while的theArray[++leftPtr]先自增了,因此這裏先減一
        int leftPtr = left - 1;
        //定義有指針,覺得內層while的theArray[++leftPtr]先自減,這裏先加一
        int rightPtr = right + 1;
        while(true)
        {
            //內層倆個while循環目的是選擇交換項
            while(leftPtr < right && theArray[++leftPtr] < value)
            {
                
            }
            while(rightPtr > left && theArray[--rightPtr] > value)
            {
                
            }
            //若是倆個指針相遇,則中止劃分,劃分結束
            if(leftPtr >= rightPtr)
            {
                break;
            }
            else
            {
                //交換
                long temp = theArray[leftPtr];
                theArray[leftPtr] = theArray[rightPtr];
                theArray[rightPtr] = temp;
            }
            
        }
        return leftPtr;
    }
}

class App{
    public static void main(String[] args)
    {
        int maxSize = 16;
        ArrayPar arr;
         arr = new ArrayPar(maxSize);
        
        for(int j = 0; j < maxSize; j++)
        {
            long n = (int)(java.lang.Math.random()*199);
            arr.insert(n);
        }
        arr.display();
        long pivot = 99;
        System.out.print("Pivot is " +pivot);
        int size = arr.size();
        int partDex = arr.partitionIt(0, size - 1, pivot);
        System.out.println(",Partition is at index" + partDex);
        arr.display();    
    }
}
相關文章
相關標籤/搜索