title: Find k - smallest element (Java code)
body: <p>I want to solve the following problem: Given an unsorted array of n elements, find the first k smallest elements. To do this I want to build a max heap of size k (from the last k elements of the array) and then to scan the rest of the elements in the array. If I find a smaller element than my root element I exchange both elements and then I heapify my heap. This solution should works in O(nlogk) time and in place. However I cannot fix it (I have index out of bound exception). I tried to debug it but I don't see where is my mistake. This is my code:</p>
  
  <pre><code>public class KSmallest {
      private static int[] a;
      private static int n;
  
      public static void buildheap(int []a){
          n=a.length-1;
          for(int i=n;i&gt;=0;i--){
              maxheap(a,i);
          }
          for (int i = n-1; i &gt;= 0; i--) {
              if(a[i]&lt;a[start]){
                  exchange(i, 0);
                  maxheap(a, 0);
              }
          }
      }
  
      public static void exchange(int i, int j){
          int t=a[i];
          a[i]=a[j];
          a[j]=t;
      }
  
      public static void sort(int []a0){
          a=a0;
          for(int i=n; i&gt;0; i--){
              exchange(0, i);
              n=n-1;
              maxheap(a, 0);
          }
      }
  
      public static void main(String[] args) {
          int []a1={4,1,3,2,7, 2, 1, 4};
          int start = a1.length-k;
          for(int i=start;i&lt;a1.length;i++){
              System.out.print(a1[i] + " ");
          }
          System.out.println();
          //sort(a1);
          for(int i=start;i&lt;a1.length;i++){
              System.out.print(a1[i] + " ");
          }
      }
  }
  </code></pre>
  
  <p>I'm struggling with this for two days so I hope anyone can help.</p>