据说是淘宝面试题“给定一个数组将大于0的放在最右边,等于0的放在中间,大于0的放在最左边”
给定一个数组将大于0的放在最右边,等于0的放在中间,大于0的放在最左边;
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #define random (rand()%10-5) 5 void swap(int *a, int *b)//交换两个整型数 6 { 7 int t = *a; 8 *a = *b; 9 *b = t; 10 } 11 12 void move_array(int a[], int n) 13 { 14 int *low = a, *high = a + n-1; 15 while(low < high) 16 { 17 while(*low < 0 && low < high) low++; 18 while(*high > 0 && high > low) high--; 19 if(low < high) 20 swap(low, high); 21 } 22 //循环结束后low一定等于high且指向大于等于0的数 23 //第二步,从low开始,将等于0得数移到左边 24 high = a + n-1; 25 while(low < high) 26 { 27 while(*low == 0 && low < high) low++; 28 while(*high > 0 && high > low) high--; 29 if(low < high) 30 swap(low, high); 31 } 32 } 33 int main() 34 { 35 srand(time(NULL)); 36 int a[10]; 37 int i; 38 for(i = 0; i < 10; i++) 39 { 40 a[i] = random; 41 } 42 move_array(a, 10); 43 for(i = 0; i < 10; i++) 44 { 45 printf("%-5d", a[i]); 46 } 47 printf("\n"); 48 49 return 0; 50 }