Friday, January 29, 2016

Largest 10 numbers

Largest 10 numbers


Find a largest 10 numbers from 1 million unsorted numbers.
Here is simple example i/p: {1,2,3,4,5,10,9,8,7,6,11,12,13,14,15,20,8,5,21,25}
o/p: 25 21 20 15 14 13 12 11 10 9
Algo:
Step1: Take first 10 numbers into one array (call it as largest numbers array) and sort it using insertion sort
Step2: Compare 11th number onwards with minimum value of sorted array until end of 1 million numbers
if a[i] > minimum value of largest numbers array then
Replace minimum value of largest numbers array with a[i]
Sort the largest numbers array
Step3: Return largest numbers array
Sol:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int[] LargestTenNumbers(int[] a)
    {
        int[] largestNums = new int[10];
        int i;
         
        //Insert first 10 numbers into largestNums array
        for(i=0; i<10; i++)
        {
            largestNums[i]=a[i];
        }
         
        //Sort first 10 numbers of largestNums array in descending order
        InsertionSort(largestNums);
         
        // Go through the remaining numbers, replace min value of largestNums array
        // with larger value if any and then sort the largestNums array
        for(;i<a.length;i++)
        {
            if(a[i]>largestNums[9])
            {
                // replace minimum value
                largestNums[9]=a[i];
                 
                // sort the largestNums array in descending order
                InsertionSort(largestNums);
            }
        }
         
        return largestNums;
    }
      
     /**
      * Insertion sort in descending order
      * @param a
      */
    void InsertionSort(int[] a)
    {
        for(int i=1; i<a.length; i++)
        {
            int value=a[i]; int j;     
            for (j=i; j>0 && a[j-1]<value; j--)
            {
                a[j]=a[j-1];
            }
            a[j]=value;
        }
    }
    

No comments:

Post a Comment