Java數據結構與算法(第七章高級排序2)

劃    分java

        劃分數據就是把數據分爲兩組,使全部關鍵字大於特定值的數據項在一組,是全部關鍵字小於特定值的數據項在另外一組。
算法

package com.gaojipaixu.partition;

public 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 i = 0; i < nElems; i++) {
            System.out.print(theArray[i]+" ");
        }
        System.out.println("");
    }
    
    public int partitionIt(int left,int right,long pivot){
        int leftPtr = left-1;
        int rightPtr = right+1;
        while(true){
            while(leftPtr<right && 
                theArray[++leftPtr]<pivot)
                ;
            while(rightPtr>left && 
                theArray[--rightPtr]>pivot)
                ;
            if(leftPtr >= rightPtr)
                break;
            else{
                long temp ;
                temp = theArray[leftPtr];
                theArray[leftPtr] = theArray[rightPtr];
                theArray[rightPtr] = temp;
            }
        }
        return leftPtr;
    }
}
public static void main(String[] args) {
		int maxSize = 16;
		Arraypar arr ;
		arr = new Arraypar(maxSize);
		for (int i = 0; i < maxSize; i++) {
			long n = (int)(java.lang.Math.random()*199);
			arr.insert(n);
		}
		arr.display();
		
		long pivot = 99;
		
		System.out.println("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();
		
	}
	
//輸出:
A=170 142 81 128 131 39 16 186 84 35 46 195 174 114 144 103 
Pivot is 99
,Partition is at index 6
A=46 35 81 84 16 39 131 186 128 142 170 195 174 114 144 103

        能夠看出劃分是成功的:前6個數字都比樞紐99小;後8個數字則都大於樞紐。
數組

        注意劃分的過程不必定要像這個例子同樣把數組劃分紅大小相同的兩半;這取決於樞紐及數據關鍵字的值。有可能一組中數據項個數多於另外一組的數據項個數。
dom

    劃分算法
spa

        劃分算法由兩個指針開始工做,兩個指針分別指向數組的兩頭。(這裏使用「指針」這個詞是指示數組數據項的,而不是C++中所說的指針。)在左邊的指針,leftPtr,向右移動,而在右邊的指針,rightPtr,向左移動。
指針

        實際上,leftPtr初始化是時在第一個數據項的左邊一位,rightPtr是在最後一個數據項的右邊一位,這是由於在它們工做以前,它們都要分別的加一和減一。
code

        中止和交換
ip

        當leftPtr遇到比樞紐小的數據項時,它繼續右移,由於這個數據項的位置已經處在數組的正確一邊了。可是,當遇到比樞紐大的數據項時,它就停下來,相似的,當rightPrt遇到大於樞紐的數據項時,它繼續左移可是當發現比樞紐小的數據項時,它也停下來。當兩個內層的while循環,第一個應用leftPtr,第二個應用於rightPrt,控制這個掃描過程。由於指針退出了while循環,因此它中止移動。下面是一段掃描不在適當位置上的數據項的簡化代碼:
element

while(theArray[++leftPtr] < pivot) //find bigger item
    ;    //(nop)
while(theArray[--right]>pivot)   //find smaller item
    ;    //(nop)
swap(lefgPtr,rightPtr);            //swap elements

            第一個while循環在發現比樞紐大的數據項時退出;第二個循環在發現小的數據項時退出。當這兩個循環都退出以後,leftPtr和rightPrt都指着在數組的錯誤一方位置上的數據項,因此交換着兩個數據項。
it






























256

相關文章
相關標籤/搜索