fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void cycleSort (int arr[], int n)
  5. {
  6. // count number of memory writes
  7. int writes = 0;
  8.  
  9. // traverse array elements and put it to on
  10. // the right place
  11. for (int cycle_start=0; cycle_start<=n-2; cycle_start++)
  12. {
  13.  
  14. int item = arr[cycle_start];
  15.  
  16. cout<<"item 1: "<<arr[cycle_start]<<endl;
  17.  
  18.  
  19. int pos = cycle_start;
  20.  
  21. for (int i = cycle_start+1; i<n; i++)
  22. if (arr[i] < item)
  23. pos++;
  24.  
  25. cout<<"Pos 1 value "<<pos<<" and array value at pos is "<<arr[pos] <<endl;
  26.  
  27. if (pos == cycle_start)
  28. continue;
  29.  
  30.  
  31. while (item == arr[pos])
  32. pos += 1;
  33.  
  34. cout<<"array element at pos 1: "<<arr[pos]<<endl;
  35.  
  36. if (pos != cycle_start)
  37. {
  38. cout<<"inside first swap"<<endl;
  39. swap(item, arr[pos]);
  40. writes++;
  41. }
  42.  
  43. for(int k=0; k<n; k++)
  44. cout<<arr[k]<<"\t";
  45.  
  46. cout<<endl;
  47.  
  48.  
  49. while (pos != cycle_start)
  50. {
  51.  
  52. cout<<"inside while 2"<<endl;
  53.  
  54. cout<<"item 2: "<<arr[cycle_start]<<endl;
  55.  
  56. pos = cycle_start;
  57.  
  58.  
  59. for (int i = cycle_start+1; i<n; i++)
  60. if (arr[i] < item)
  61. cout<<"Pos 2: "<<pos++;
  62.  
  63. cout<<endl;
  64.  
  65.  
  66. while (item == arr[pos])
  67. {
  68. pos += 1;
  69. cout<<"inside while 3"<<endl;
  70. }
  71.  
  72.  
  73. if (item != arr[pos])
  74. {
  75. swap(item, arr[pos]);
  76. cout<<"inside if 2"<<endl;
  77. writes++;
  78. }
  79. }
  80.  
  81.  
  82. }
  83.  
  84. // Number of memory writes or swaps
  85. // cout << writes << endl ;
  86. }
  87.  
  88. int main()
  89. {
  90. int arr[] = {7,2,1,3,0,7,-1,7,4};
  91. int n = sizeof(arr)/sizeof(arr[0]);
  92. cycleSort(arr, n) ;
  93.  
  94. cout << "After sort : " <<endl;
  95. for (int i =0; i<n; i++)
  96. cout << arr[i] << " ";
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
item 1: 7
Pos 1 value 6 and array value at pos is -1
array element at pos 1: -1
inside first swap
7	2	1	3	0	7	7	7	4	
inside while 2
item 2: 7

inside if 2
item 1: 2
Pos 1 value 3 and array value at pos is 3
array element at pos 1: 3
inside first swap
-1	2	1	2	0	7	7	7	4	
inside while 2
item 2: 2
Pos 2: 1Pos 2: 2Pos 2: 3
inside if 2
inside while 2
item 2: 2

inside if 2
item 1: 1
Pos 1 value 2 and array value at pos is 1
item 1: 2
Pos 1 value 3 and array value at pos is 2
item 1: 3
Pos 1 value 4 and array value at pos is 3
item 1: 7
Pos 1 value 6 and array value at pos is 7
array element at pos 1: 4
inside first swap
-1	0	1	2	3	7	7	7	7	
inside while 2
item 2: 7

inside if 2
item 1: 7
Pos 1 value 6 and array value at pos is 7
item 1: 7
Pos 1 value 7 and array value at pos is 7
After sort : 
-1 0 1 2 3 4 7 7 7