HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Determining average of integers using quicksort

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningaveragequicksortusingintegers

Problem

I was attempting an online problem given on a programming website which asked us to tell us the number of integers in a given list which can be obtained as an average of any two other integers in that list, where one of them can be equal to the average (so the other is obviously equal too).

The server tells me that my program exceeded the time limit for the last two test cases. So I would like to make my algorithm faster.

I've tried both the inbuilt Java sort function as well as my own implementation of quicksort. I tried the test data on my own computer and it gives the output within a second.

My program basically sorts the array first, and then searches for a pair in linear time.

import java.util.*;

public class Average {

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        int[] a = new int[n];

        for (int i = 0; i p && a[j] > x){
            j--;}

        if (i < j)
            swap(a, i, j);
        else
            return j;
    }
}

}

Solution

Just a few comments:

You can't really hope that your quicksort will be faster than what Java provides. I'm not saying, it can't be done, but it'd take an excellent programmer a few days at best.

So let's forget this part... and now to your algorithm. After some reformatting, I might understand it:

int result = 0;

for (int k = 0; k  0) {
            r--;
        } else {
            result++;
            break;
        }
    }
}


You really seem to be doing what you stated. The total time is quadratic, so let's forget the sorting once again.

Some better variable naming would surely do no harm.

I'll come back when I get an idea concerning the speed.

Code Snippets

int result = 0;

for (int k = 0; k < n; k++) {
    int desired = 2 * a[k];
    int l = 0;
    int r = n-1;
    while (l < r) {
        int diff = a[l] + a[r] - desired;
        // made symmetric
        if (diff < 0) {
            l++;
        } else if (diff > 0) {
            r--;
        } else {
            result++;
            break;
        }
    }
}

Context

StackExchange Code Review Q#63443, answer score: 2

Revisions (0)

No revisions yet.