转自出处
Modified 2 color sort problem i.e. you are given an array of integers
containing only 0s and 1s.You have to place all the 0s in even position and
1s in odd position. And if suppose, no. of 0s exceed no. of 1s or vice versa
then keep them untouched. Do that in ONE PASS and without taking extra
memory (modify the array in-place).
For e.g.
Input Array: {0,1,1,0,1,0,1,0,1,1,1,0,0,1,0,1,1}
Output Array: {0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1}
分析:
1、题目一很容易联想到partition的作法,不过考虑到题目要求“if suppose no. of 0s exceed no. of 1s or vice versa then keep them untouched”,所以临界情况要特别注意,否则得到的结果很可能是类似于{0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 1 }这样的结果,显然这不是题目所要求的输出。
void RearrangeO1(int seq[],int n) { int index0 = 0; int index1 = 1; ///////////////类似于partition操作 while(true) { while(index0 < n && seq[index0] == 0 ) index0 += 2; if(index0 >= n) break; while(index1 < n && seq[index1] == 1 ) index1 += 2; if(index1 >= n) break; //////////交换 int temp = seq[index0]; seq[index0] = seq[index1]; seq[index1] = temp; } /////////////////////////临界情况处理 ////////奇数位置上已经全部为0,处理偶数位置:1尽量往前排 if(index0 >= n) { int indexend = (n % 2 == 0) ? n - 1 : n - 2; while(true) { while(index1 < n && seq[index1] == 1) index1 += 2; while(indexend > index1 && seq[indexend] == 0) indexend -= 2; if(index1 >= indexend) break; /////////交换 int temp = seq[index1]; seq[index1] = seq[indexend]; seq[indexend] = temp; } } ////////偶数位置上已经全部为1,处理奇数位置:0尽量往前排 else { int indexend = (n % 2 == 0) ? n - 2 : n - 1; while(true) { while(index0 < n && seq[index0] == 0) index0 += 2; while(indexend > index0 && seq[indexend] == 1) indexend -= 2; if(index0 >= indexend) break; /////////交换 int temp = seq[index0]; seq[index0] = seq[indexend]; seq[indexend] = temp; } } }