微软面试题目(二)移动数组元素
给定一个整数数组,将数组中小于零的数都放在最左边,等于0的放在中间,小于零的放在最右边。
代码如下:
void swap(int* a,int* b) { *a = *a ^ *b; //a、b中不同位 *b = *a ^ *b; //b = a *a = *a ^ *b; //a = b } void ArrangArray(int* StartPos,int* EndPos) { //Step1先将小于零的放在最左边,大于等于0的数不区分,都放在右边 int* low = StartPos; int* high = EndPos; while(low < high) { while( *low < 0 && low < high ) low++; while( *high >= 0 && low < high ) high--; if(low < high) swap(low,high); } //循环结束时,low一定等于high,且指向大于等于0的数 //Step2,从low开始,将等于0的数移动到左边,大于0的数移动到右边 high = EndPos; while(low < high) { while( *low == 0 && low < high ) low++; while( *high > 0 && low < high ) high--; if(low < high) swap(low,high); } } int main() { int array[10] = {-1,3,0,2,-5,0,-3,4,0,-8}; ArrangArray(array,array + 9); }