标签:
有一个只由0,1,2三种元素构成的整数数组,请使用交换、原地排序而不是使用计数进行排序。
给定一个只含0,1,2的整数数组A及它的大小,请返回排序后的数组。保证数组大小小于等于500。
#include <iostream> #include <vector> using namespace std; class ThreeColor { public: vector<int> sortThreeColor(vector<int> A, int n) { // write code here int tmp; int index0 = -1, index2 = n; for(int i = 0; i < index2; i++){ switch (A[i]){ case 0: { tmp = A[i]; A[i] = A[++index0]; A[index0] = tmp; break; } case 1: { continue; } case 2: { tmp = A[i]; A[i] = A[--index2]; A[index2] = tmp; i--; break; } } } return A; } }; int main() { vector<int> A; A.push_back(0), A.push_back(1), A.push_back(1), A.push_back(0), A.push_back(2), A.push_back(2), A.push_back(1), A.push_back(0), A.push_back(2), A.push_back(2); vector<int> res; ThreeColor sorter; res = sorter.sortThreeColor(A, 10); for(int i = 0; i < 10; i++){ cout<<res[i]<<" "; } cout<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/zhongzhiqiang/p/5798829.html