Search code examples
algorithmcomplexity-theory

Complexity analysis of SelectionSort


Here's a SelectionSort routine I wrote. Is my complexity analysis that follows correct?

public static void selectionSort(int[] numbers) {

    // Iterate over each cell starting from the last one and working backwards
    for (int i = numbers.length - 1; i >=1; i--)
    {
        // Always set the max pos to 0 at the start of each iteration
        int maxPos = 0;

        // Start at cell 1 and iterate up to the second last cell
        for (int j = 1; j < i; j++)
        {
            // If the number in the current cell is larger than the one in maxPos,
            // set a new maxPos
            if (numbers[j] > numbers[maxPos])
            {
                maxPos = j;
            }
        }

        // We now have the position of the maximum number. If the maximum number is greater
        // than the number in the current cell swap them
        if (numbers[maxPos] > numbers[i])
        {
            int temp = numbers[i];
            numbers[i] = numbers[maxPos];
            numbers[maxPos] = temp;
        }
    }
}

Complexity Analysis

Outter Loop (comparison & assignment): 2 ops performed n times = 2n ops

Assigning maxPos: n ops

Inner Loop (comparison & assignment): 2 ops performed 2n^2 times = 2n² ops

Comparison of array elements (2 array references & a comparison): 3n² ops

Assigning new maxPos: n² ops

Comparison of array elements (2 array references & a comparison): 3n² ops

Assignment & array reference: 2n² ops

Assignment & 2 array references: 3n² ops

Assignment & array reference: 2n² ops

Total number of primitive operations

2n + n + 2n² + 3n² + n^2 + 3n² + 2n² + 3n² + 2n² = 16n² + 3n

Leading to Big Oh(n²)

Does that look correct? Particularly when it comes to the inner loop and the stuff inside it...


Solution

  • Yes, O(N2) is correct.

    Edit: It's a little hard to guess at exactly what they may want as far as "from first principles" goes, but I would guess that they're looking for (in essence) something on the order of a proof (or at least indication) that the basic definition of big-O is met:

    there exist positive constants c and n0 such that:

    0 ≤ f(n) ≤ cg(n) for all n ≥ n0.

    So, the next step after finding 16N2+3N would be to find the correct values for n0 and c. At least at first glance, c appears to be 16, and n0, -3, (which is probably treated as 0, negative numbers of elements having no real meaning).