Heaps: Find the Running Median

  • + 0 comments

    This works fine, but as I understand time complexity if O(n^2) due to add operation

    List<Integer> aList = new ArrayList(n);
            Collections.fill(aList, Integer.MAX_VALUE);
    
            int lastIndex = -1;
            for (int i = 0; i < n; i++) {
                int aItem = scanner.nextInt();
                scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    
                int index = Collections.binarySearch(aList, aItem);
                if (index < 0) {
                    index = Math.abs(index) - 1;
                }
                aList.add(index, aItem);
    
                lastIndex++;
    
                if ((lastIndex + 1) % 2 == 0) {
                    int item1 = aList.get((lastIndex + 1) / 2);
                    int item2 = aList.get(((lastIndex + 1) / 2) - 1);
                    System.out.println((item1 + item2) / 2.0);
                } else {
                    System.out.println(aList.get((lastIndex + 1) / 2) / 1.0);
                }
            }