public virtual void wiggleSort(int[] arr) { if (arr.Length == 0) { return; } int k = arr.Length / 2; KthElementInArray kthElementInArray = new KthElementInArray(); kthElementInArray.kthElement(arr, k); int mid = arr[k]; int n = arr.Length; int i = 0, j = 0; k = n - 1; while (j <= k) { if (arr[next(j, n)] > mid) { swap(arr, next(i++, n), next(j++, n)); } else if (arr[next(j, n)] < mid) { swap(arr, next(j, n), next(k--, n)); } else { j++; } } }
public virtual void convert(int[] arr) { int k = 0; if (arr.Length % 2 == 0) { k = arr.Length / 2; } else { k = arr.Length / 2 + 1; } KthElementInArray kthElement = new KthElementInArray(); kthElement.kthElement(arr, k); int high = k; int low = 1; while (low < high && high < arr.Length) { swap(arr, low, high); high++; low += 2; } }
public static void Main(String[] args) { /* * Kth largest element in an array. * Use quickselect of quicksort to find the solution * in hopefully O(nlogn) time. * Test cases * Sorted array * Reverse sorted array */ int[] arr = { 4, 3, 2, 1 }; KthElementInArray kthElement = new KthElementInArray(); Console.WriteLine(kthElement.kthElement(arr, 2)); }