算法练习:两指针之三色排序

问题描述

输入一个整型数组,每个元素在0~2之间,其中012分别代表红、白、蓝。现要求对数组进行排序,相同颜色的在一起,而且按红白蓝顺序先后排列。要求时间复杂度为O(n)

 

问题分析

最容易想到的是排序,比如快排,归并,堆排等,但它们的时间复杂度为O(nlogn),与题意不符。

第二种想到的是计数排序,扫描一遍过去,分别记录012的个数,然后再对数组进行赋值。时间复杂度为O(2n),即O(n),满足条件。

还有一种方法,只需扫描一遍数组即可,其充分利用了元素只有3种的特性:在扫描数组的时候,使用首尾俩个指针,分别指示0112边界。比如源数组为{2, 2, 0, 0, 1, 1  }

 

第一步:首指针p0,尾指针p1i标识当前扫描位置,当前位置值为2需要将其交换至尾指针p1位置,p1要向前移动一位,p0i位置不变。

《算法练习:两指针之三色排序》

第二步:i位置值不为02i要向后移动一位,p0p1位置不变。

《算法练习:两指针之三色排序》

第三步:i位置值为2,需要将其交换至尾指针p1位置,并且p1往前移动一位,ip0位置不变。

《算法练习:两指针之三色排序》

第四步:i位置不为02,i要向后移动一位,p0p1位置不变。

《算法练习:两指针之三色排序》

第五步:i位置值为0,需要将其交换至首指针p0位置,并且p0往后移动一位,ip1位置不变。

《算法练习:两指针之三色排序》

第六步:i位置不为02,i要向后移动一位,p0p1位置不变。

《算法练习:两指针之三色排序》

第七步:i位置值为0,需要将其交换至首指针p0位置,并且p0往后移动一位,ip1位置不变。

 《算法练习:两指针之三色排序》

 

第八步:i位置不为02,i要向后移动一位,p0p1位置不变。

《算法练习:两指针之三色排序》

第九步:i位置超过p1位置了,结束。

 

实现代码

#include <iostream>

using namespace std;

void ThreeColorSort( int nArray[], int nCount )
{
	int p0 = 0;			//首指针
	int p1 = nCount-1;	//尾指针


	int i = 1;
	while( i <= p1 )
	{
		//当前值为2,与尾指针p1指向的值相互交换,p1向前移动一位
		//i、p0位置不变
		if ( nArray[i] == 2 )
		{
			int nTemp = nArray[i];
			nArray[i] = nArray[p1];
			nArray[p1--] = nTemp;
		}
		//当前值为0,与首指针p0指向的值相互交换,p0向后移动一位
		//i、p0位置不变
		else if ( nArray[i] == 0 && i > p0 )
		{
			int nTemp = nArray[i];
			nArray[i] = nArray[p0];
			nArray[p0++] = nTemp;
		}
		//i位置不为0、2,i要向后移动一位,p0、p1位置不变。
		else
		{
			++i;
		}
	}
}


//书上的例子代码
void SortColors( int nArray[], int nCount )
{
	int p0 = 0;
	int p2 = nCount;
	for( int i = 0; i < p2; ++i )
	{
		if ( nArray[i] == 0 )
		{
			int tmp = nArray[p0];
			nArray[p0] = nArray[i];
			nArray[i] = tmp;
			++p0;
		}
		else if ( nArray[i] == 2 )
		{
			--p2;
			int tmp = nArray[p2];
			nArray[p2] = nArray[i];
			nArray[i] = tmp;
			--i;
		}
	}
}



int main()
{
	//int nArray[] = { 2, 1, 0, 2, 0 };
	//int nArray[] = { 0, 0, 1, 1, 2, 2 };
	//int nArray[] = { 0 };
	//int nArray[] = { 2, 0, 1 };
	int nArray[] = { 2, 2, 0, 0, 1, 1 };
	ThreeColorSort( nArray, _countof(nArray) );

	//SortColors( nArray, _countof(nArray) );
	for( int i = 0; i < _countof(nArray); ++i )
	{
		cout << nArray[i] << " ";
	}
	cout << endl;


	return 0;
}

系列文章说明:
1.本系列文章[算法练习],仅仅是本人学习过程的一个记录以及自我激励,没有什么说教的意思。如果能给读者带来些许知识及感悟,那是我的荣幸。
2.本系列文章是本人学习陈东锋老师《进军硅谷,程序员面试揭秘》一书而写的一些心得体会,文章大多数观点均来自此书,特此说明!
3.文章之中,难免有诸多的错误与不足,欢迎读者批评指正,谢谢.

作者:山丘儿
转载请标明出处,谢谢。原文地址:http://blog.csdn.net/s634772208/article/details/46740191

    原文作者:排序算法
    原文地址: https://blog.csdn.net/s634772208/article/details/46740191
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞