K-Smallest Elements In An Array

K-Smallest Elements In An Array

Find the k-smallest elements in an array of A of n elements.
Kth Index Algorithm:
  1. Find pivot_index using partition
  2. Iterate till k-l !=
    1. if k-1 < pivot_index then
      1. Set end = pivot_index – 1
    2. else
      1. Set start = pivot_index + 1
    3. Recursively call with start and end
  3. return pivot_index
Partition Algorithm:
  1. Set pivot = array[end]
  2. Set pivot_index = start
  3. Iterate from start to end of
    1. If array[i] < pivot then
      1. Swap ith index data with pivot_index data
      2. Increase pivot_index by 1
  4. Swap pivot_index with end_index
  5. return pivot_index

Source Code:
Github: KSmallestFinder.java


Output:

Before sort: 7 3 18 9 1 2 15 12 5 
After sort: 1 2 3 5 7 9 12 15 18     
Author: Hrishikesh Mishra