Guest User

Untitled

a guest
Jun 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. //
  2. using System;
  3.  
  4. class Solution
  5. {
  6. public static int[] SortKMessedArray(int[] arr, int k) // [2, 3, 1, 4], k = 2
  7. {
  8. if(arr == null || k < 0) // false
  9. {
  10. return new int[0];
  11. }
  12.  
  13. // work on selection sort, iterate on the array
  14. int index = 0;
  15. var length = arr.Length; // 4
  16.  
  17. while(index < length)
  18. {
  19. selectionSortToPlaceMinimumInPlace(arr, index++, k + 1 );
  20. }
  21.  
  22. return arr;
  23. }
  24.  
  25. private static void selectionSortToPlaceMinimumInPlace(int[] numbers, int start, int totalNumber)// 0, 3
  26. {
  27. var length = numbers.Length; // 4
  28.  
  29. for(int index = start; index < length && (index - start) < totalNumber; index++) // 0, 1, 2
  30. {
  31. if(numbers[index] < numbers[start]) //
  32. {
  33. // swap two elements
  34. var tmp = numbers[start];
  35. numbers[start] = numbers[index]; // 1
  36. numbers[index] = tmp; // 2
  37. }
  38. }
  39. }
  40.  
  41. static void Main(string[] args)
  42. {
  43. // [1, 2, 3, 4], k = 2
  44. // [2, 3, 1, 4]
  45. var sorted = SortKMessedArray(new int[]{2, 3, 1, 4}, 2) ;
  46. foreach(var item in sorted)
  47. {
  48. Console.WriteLine(item);
  49. }
  50. }
  51. }
  52.  
  53. /*
  54. keywords:
  55.  
  56. given array integer, sorted original, then each element can be moved away at most k places
  57.  
  58. For example:
  59. [1, 2, 3, 4], 1 move to index = 2 from index = 0 if k = 2
  60.  
  61. Ask: sort the array
  62.  
  63. Solution 1: optimal
  64.  
  65. minimum heap:
  66.  
  67. k = 2, minimum heap size = 3
  68.  
  69. 1
  70. /\
  71. 2 3
  72.  
  73. k + 1 , minimum number in the heap is minimum in the array -> pop heap -> next element 4, push 4 into heap
  74.  
  75. 2
  76. /\
  77. 3 4
  78.  
  79. Time complexity: O(klogK + n * logK)
  80.  
  81. C# heap class -> C# does not have class for heap ->
  82.  
  83. Solution 2:
  84.  
  85. selection sort
  86.  
  87. Find minimum in k + 1 subarray
  88.  
  89. [1, 2, 3, 4], given k = 2, work on subarray with size 3 = K + 1
  90. [1, 2, 3] -> selection sort -> find minimum value
  91. k + 1 time to find minimum value
  92.  
  93. For whole array, time complexity O(n * (k + 1)) which is better than O(nlogn), k << n
  94.  
  95. */
Add Comment
Please, Sign In to add comment