fork download
  1. #include <stdio.h>
  2.  
  3. void swap( int* a, int* b )
  4. {
  5. int temp = *a;
  6. *a = *b;
  7. *b = temp;
  8. }
  9.  
  10. void sortTwoColor( int* a, int len )
  11. {
  12. int i, j;
  13.  
  14. i = 0;
  15. j = 1;
  16.  
  17. while(i < len && j < len)
  18. {
  19. if(a[i] && !a[j])
  20. {
  21. a[i] = 0;
  22. a[j] = 1;
  23. i += 2;
  24. j += 2;
  25. }
  26.  
  27. if(!a[i])
  28. i += 2;
  29.  
  30. if(a[j])
  31. j += 2;
  32. }
  33.  
  34. int t = i;
  35. while(i < len)
  36. {
  37. if(!a[i])
  38. {
  39. a[t] = 0;
  40. a[i] = 1;
  41. t += 2;
  42. }
  43. i += 2;
  44. }
  45.  
  46. t = j;
  47. while(j < len)
  48. {
  49. if(a[j])
  50. {
  51. a[t] = 1;
  52. a[j] = 0;
  53. t += 2;
  54. }
  55. j += 2;
  56. }
  57. for( i = 0; i < len; ++i )
  58. printf( "%d ", a[i] );
  59. }
  60.  
  61. int main()
  62. {
  63. int arr[] = {0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0};//{ 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1 };
  64. int size = sizeof( arr ) / sizeof( *arr );
  65.  
  66. sortTwoColor( arr, size );
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0.02s 1676KB
stdin
Standard input is empty
stdout
0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1