fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5.  
  6. void cocktail_sort(int *data, int n)
  7. {
  8. int i, tmp, k, left, right = n-1, shift = -1;
  9.  
  10.  
  11.  
  12. while((left=shift) < right)
  13. {
  14. for(i = left+1; i < right; i++)
  15. {
  16. if (data[i] > data[i+1])
  17. {
  18. tmp = data[(shift=i)];
  19. data[i] = data[i+1];
  20. data[i+1] = tmp;
  21.  
  22. for(k = 0; k < n; k++)
  23. if (k == i || k == i+1) printf("[%2d] ", data[k]); else printf(" %2d ", data[k]);
  24. printf("\n");
  25. }
  26. else { for(k = 0; k < n; k++) printf(" %2d ", data[k]); printf("\n"); }
  27. }
  28. printf("\n");
  29.  
  30. for(i = (right=shift)-1; i > left; i--)
  31. {
  32. if (data[i] > data[i+1])
  33. {
  34. tmp = data[(shift=i)];
  35. data[i] = data[i+1];
  36. data[i+1] = tmp;
  37.  
  38. for(k = 0; k < n; k++)
  39. if (k == i || k == i+1) printf("[%2d] ", data[k]); else printf(" %2d ", data[k]);
  40. printf("\n");
  41. }
  42. else { for(k = 0; k < n; k++) printf(" %2d ", data[k]); printf("\n"); }
  43. }
  44. printf("\n");
  45. }
  46. }
  47.  
  48.  
  49.  
  50. int main()
  51. {
  52. int i, n = 6;
  53. int data[6] = { 40, 25, 13, 17, 75, 7 };
  54.  
  55. printf("========== 정렬 전 ==========\n");
  56. for(i = 0; i < n; i++) printf(" %2d ", data[i]); printf("\n");
  57.  
  58.  
  59.  
  60. printf("\n========== 정렬 ==========\n");
  61. cocktail_sort(data, n);
  62.  
  63.  
  64.  
  65. printf("========== 정렬 후 ==========\n");
  66. for(i = 0; i < n; i++) printf(" %2d ", data[i]); printf("\n");
  67.  
  68. system("pause");
  69. return 0;
  70. }
Success #stdin #stdout #stderr 0s 4448KB
stdin
Standard input is empty
stdout
========== 정렬 전 ==========
 40   25   13   17   75    7  

========== 정렬 ==========
[25] [40]  13   17   75    7  
 25  [13] [40]  17   75    7  
 25   13  [17] [40]  75    7  
 25   13   17   40   75    7  
 25   13   17   40  [ 7] [75] 

 25   13   17  [ 7] [40]  75  
 25   13  [ 7] [17]  40   75  
 25  [ 7] [13]  17   40   75  
[ 7] [25]  13   17   40   75  

  7  [13] [25]  17   40   75  
  7   13  [17] [25]  40   75  
  7   13   17   25   40   75  

  7   13   17   25   40   75  

========== 정렬 후 ==========
  7   13   17   25   40   75  
stderr
sh: 1: pause: not found