您的位置:首页 > 其它

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

2017-04-27 13:47 302 查看

问题描写叙述

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

问题分析

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

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

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

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



第二步:i位置值不为0、2,i要向后移动一位。p0、p1位置不变。



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



第四步:i位置不为0、2,i要向后移动一位,p0、p1位置不变。



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



第六步:i位置不为0、2。i要向后移动一位,p0、p1位置不变。



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



第八步:i位置不为0、2,i要向后移动一位,p0、p1位置不变。



第九步: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: