Guest User

Untitled

a guest
Feb 23rd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. public static int[] PancakeSort(int[] arr)
  6. {
  7. if(arr == null || arr.Length == 0)
  8. {
  9. return new int[0];
  10. }
  11.  
  12. var lastIndex = arr.Length - 1;
  13.  
  14. int index = 0;
  15.  
  16. while(index < length)
  17. {
  18. var lastPosition = lastIndex - index;
  19.  
  20. var maxIndex = findMaxIndex(arr, lastIndex - index);
  21. inplaceMove(arr, maxIndex, lastPosition);
  22.  
  23. index++;
  24. }
  25.  
  26. return arr;
  27. }
  28.  
  29. private static int findMaxIndex(int[] arr, int lastPos)
  30. {
  31.  
  32. int maxIndex = 0;
  33. for(int i = 1; i <= lastPos; i++)
  34. {
  35. if(arr[i] > arr[maxIndex])
  36. {
  37. maxIndex = i;
  38. }
  39. }
  40.  
  41. return maxIndex;
  42. }
  43.  
  44. private static void inplaceMove(int[] arr, int maxIndex, int lastPosition)
  45. {
  46. flip(arr, maxIndex + 1);
  47. flip(arr, lastPosition + 1);
  48. }
  49.  
  50. // flip first k element 0 - k- 1
  51. private static void flip(int[] arr, int k)
  52. {
  53. int start = 0;
  54. int end = k - 1;
  55.  
  56. while(start < end)
  57. {
  58. var tmp = arr[start];
  59. arr[start] = arr[end];
  60. arr[end] = tmp;
  61.  
  62. start++;
  63. end--;
  64. }
  65. }
  66.  
  67. static void Main(string[] args)
  68. {
  69.  
  70. }
  71. }
  72.  
  73. /*
  74. [1, 5, 4, 3, 2]
  75.  
  76. [0, 1, 0,1, 1]
  77.  
  78. 1 2 3 4 5
  79. 0 1 1 0 1
  80.  
  81. [1 4 ] [2 3 5]
  82. 0 0 1 1 1
  83.  
  84. -> maxIndex -
  85. 1
  86. API moveFromOneToLastPlace
  87.  
  88. flip first index + 1, max value is the first in the array
  89. flip first lastPos + 1, 4, flip first 5 element, go to last position
  90.  
  91. [1, 5, 4, 3, 2 ]
  92. */
Add Comment
Please, Sign In to add comment