荷兰三色旗问题 Dutch national flag problem

算法详解见此网址: http://www.geeksforgeeks.org/archives/8133


我的C++语言实现

#include <iostream>

void swap(int* a, int* b)
{
	*a = *a + *b;
	*b = *a - *b;
	*a = *a - *b;
};

int main()
{
	int a[] = {1,0,0,0,1,1,0,0,2,2,2,1,1,0,0,0};

	int len = sizeof(a) / sizeof(int);

	std::cout << "Original list:\n";
	int i = 0;
	while(i < len)
	{
		std::cout << a[i] << " ";
		i++;	
	}

	std::cout << "\n";

	int left = 0;
	int mid = 0;
	int right = len - 1;

	while(mid < right)
	{
		switch(a[mid])
		{
		case 0:
			swap(&a[left++], &a[mid]);
			break;
		case 1:
			mid++;
			break;
		case 2:
			swap(&a[mid], &a[right--]);
			break;
		}
	}

	std::cout << "Sorted list:\n";
	i = 0;
	while(i < len)
	{
		std::cout << a[i] << " ";
		i++;	
	}
	return 0;
}


你可能感兴趣的:(荷兰三色旗问题 Dutch national flag problem)