Monday, November 2, 2015

[Quick select algorithm]find the Kth element in a list in linear time

Source:http://cse-wiki.unl.edu/wiki/index.php/Sorting_Algorithms


Random select.jpg

Source: http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
Arr = [5 1 4 3 2]
Pivot = [4]

Steps:

swap [5] and [2] as 5>=4 and 2<
[2 1 4 3 5]

swap [4] and [3] as 4>=4 and 3<4
[2 1 3 4 5]


Arr = [2 1 3 …]
Pivot = [1]

Steps:
swap [2] and [1] as 2>=2 and 1<2
[1 2 3 …]



Arr = […2 3…]
Pivot= [2]

// Quick Select O(n) instead of O(nlogn) for large dataset

// Source :http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
public static int selectKth(int[] arr, int k) {
 if (arr == null || arr.length <= k)
  throw new Error();
 
 int from = 0, to = arr.length - 1;
 
 // if from == to we reached the kth element
 while (from < to) {
  int r = from, w = to;
  int mid = arr[(r + w) / 2];
 
  // stop if the reader and writer meets
  while (r < w) {
 
   if (arr[r] >= mid) { // put the large values at the end
    int tmp = arr[w];
    arr[w] = arr[r];
    arr[r] = tmp;
    w--;
   } else { // the value is smaller than the pivot, skip
    r++;
   }
  }
 
  // if we stepped up (r++) we need to step one down
  if (arr[r] > mid)
   r--;
 
  // the r pointer is on the end of the first k elements
  if (k <= r) {
   to = r;
  } else {
   from = r + 1;
  }
 }
 
 return arr[k];
}

No comments:

Post a Comment