描述:
將三種顏色作為012,要求將無序數組排為有序。
思路:
1.遍歷,記錄0,1,2的個數,然后重寫數組。O(N)的時間復雜度。需要額外空間
2.采用交換的思想,遍歷數組,將無序的數字交換到前后。O(N)的時間復雜度。空間復雜度O(1)。
代碼:
public void ThreeSort(int[] arr,int len)
{
int begin=0;
int end=len-1;
int current=0;
while(current<=end) //從交換來的棋子是0,又恰好current==end,此時還要判斷。
{
if(arr[current]==0)
{
SWAP(arr,begin,current);
begin++;
current++; //從左邊開始移動的能保證current左方的值一定是0;
}
else if(arr[current]==1)
{
current++;
}
else if(arr[current]==2)
{
SWAP(arr,end,current);
end--; //交換過來的可能是0,current不能移動
}
}
}