荷蘭國旗問題:


何謂荷蘭國旗:

現有紅、白、藍三個不同顏色的小球,亂序
排列在一起,請重新排列這些小球,使得紅
白藍三色的同顏色的球在一起。這個問題之
所以叫荷蘭國旗,是因為我們可以將紅白藍
三色小球想象成條狀物,有序排列后正好組
成荷蘭國旗。

 

問題轉換為:給定數組A[0…N-1],元素只能取0、
1、2三個值,設計算法,使得數組排列成
“00…0011…1122…22”的形式。
 借鑒快速排序中partition的過程。定義三個指針:
begin=0、current=0、end=N-1:
 A[cur]==2,則A[cur] 與A[end]交換,end--,cur不變
 A[cur]==1,則cur++,begin不變,end不變
 A[cur]==0,則:
 若begin==cur,則begin++,cur++
 若begin≠cur,則A[cur]與A[begin]交換,begin++,cur不變

 

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

void  Holland(int* a, int length)
{
    int begin = 0;
    int currentNum = 0;
    int end = length - 1;
    while (currentNum <= end)
    {
        if (a[currentNum] == 2)
        {
            swap(a[end], a[currentNum]);
            end--;
        }
         else if (a[currentNum] == 1)
        {
            currentNum++;
        }
        else
        {
            if (begin == currentNum)
            {
                begin++;
                currentNum++;
            }
            else
            {
                swap(a[currentNum], a[begin]);
                begin++;
            }
        }
    }
}

int main()
{
    int a[] = { 1, 2, 0, 1, 2, 0, 1, 2, 1, 0, 2 };//原數組    
    int n = sizeof(a) / sizeof(int);//數組長度  
    for (int i = 0; i<n; i++)
        cout << a[i];   //輸出原來的數組 
    cout << endl;
    Holland(a, n);
    for (int j = 0; j<n; j++)
        cout << a[j];
    cout << endl;
    getchar();
    return 0;
}

輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM