Merge K sorted Arrays debud it

import java.util.*;
public class Main {
public static void main(String args[]) {
Heap heap = new Heap();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] arr = new int[n][m];
for(int i = 0; i<n;i++){
for(int j =0; j<m;j++){
arr[i][j] = scan.nextInt();
//System.out.println(arr[i][j]);
heap.add(arr[i][j]);

      }
  }  
  heap.display();

}

}
class Heap{
ArrayList heap = new ArrayList<>();
public void add(int item){
heap.add(item);
int ci = heap.size()-1;

    unheapify(ci);

}
private void unheapify(int ci){ 
    int pi = (ci-1)/2;
    if(heap.get(ci)<heap.get(pi))
    {
        swap(pi,ci);
        unheapify(pi);
    }
}
private void swap(int pi,int ci){
    int ith = heap.get(pi);
    int jth = heap.get(ci);
    heap.set(pi,jth);
    heap.set(ci,ith);
}
Collections.sort(heap);
public void display(){
    for(int i=0; i<heap.size();i++){
        System.out.print(heap.get(i)+ " ");
    }
}

}

Your code is giving an error because you haven’t defined the datatype for the Arraylist in this line. However, even after that, there is some problem with the logic. From your code, I can understand that you have tried to put all the elements into a heap and then displayed the heap. But when your heap is created, and upheapify is called, it only compares the children with its parent elements. So, your resultant array will not be sorted properly. See (https://drive.google.com/open?id=1-MGS_psvQ2vG9xRoLdQAZw7NjoXRKhRb). This will be the resultant tree formed and hence answer comes out to be 0 1 4 2 3 5 6 8 7 9 10.

You will have to change your logic, and please don’t use collections.sort and use properties of heap to get your answer. As a hint, keep only K elements in the heap at a time, where K is the number of arrays.

Since you have not responded for a long time, I am closing this thread. If you still have queries about this, you can open the doubt again.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.