Find the top 10 out of a million. Write code and analyze complexity.

Keywords: Java

Title: find the 10 largest numbers out of 1 million. Write code and analyze complexity.

Analysis:

Take out the first 10 numbers of this group of data and build a small root heap (heap sorting: sort 10 numbers in ascending order, build a large root heap first, and then exchange the maximum value at the top of the heap with the last value, so as to keep cycling until the arrangement becomes a small root heap). This heap will store the maximum 10 numbers in the data, and then traverse the remaining data, and directly skip the elements smaller than the top of the heap. , replace the top element of the heap, and then maintain the heap (that is, the process of sorting). After traversing the array, the heap holds the largest 10 elements.

Complexity: O (n)

A heap with a maintenance length of 10 is negligible for traversing a large amount of data, so the complexity is the traversal complexity O(n).

Code:

import java.util.Arrays;
public class Sort {
    public static void main(String[] args) {
        int[] arr = new int[1000000];
        for(int i=0;i<arr.length; i++){
           arr[i] = i+1;
        }
        int[] result = sort(arr,10);
        System.out.println(Arrays.toString(result));
    }
    public static int[] sort(int[]arr, int n){
        int[] result = new int[n];
        System.arraycopy(arr,0,result,0,n);
        //Adjust to large root heap
        for(int i=n-1; i>=0; i--){
            adjustDown(result,i,n);
        }
        //Maintenance: becoming a small root heap
        maintainHeap(result);
        //Traverse the remaining data and maintain the small root heap
        for(int i=n; i<arr.length; i++) {
            if(arr[i] > result[0]){
                result[0] = arr[i];
                maintainHeap(result);
            }
        }
        return result;
    }

    /**
     * Maintenance of small root pile
     * @param arr
     */
    private static void maintainHeap(int[] arr) {
        int tmp = 0;
        int end = arr.length-1;
        while(end > 0){
            tmp = arr[0];
            arr[0] = arr[end];
            arr[end] = tmp;
            adjustDown(arr,0,end);
            end--;
        }
    }

    /**
     * Downward adjustment
     * @param arr
     * @param i
     */
    private static void adjustDown(int[] arr, int i,int len) {
        int c = 2*i+1;//Left child
        int tmp = 0;
        while(c<len){
            c = c+1<len ? (arr[c]<arr[c+1]?c+1:c):c;//Biggest child
            if(arr[c] >arr[i]){
                tmp = arr[c];
                arr[c] = arr[i];
                arr[i] = tmp;
                i=c;
                c=2*i+1;
            }else{
                break;
            }
        }
    }
}

 

Posted by adwfun on Tue, 15 Oct 2019 13:07:41 -0700