SelectionSort difficulty analysis

Here is the SelectionSort program I wrote. Is my complexity analysis 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;
        }
    }
}

Difficulty analysis

Outter Loop (comparison and purpose): 2 ops completed n times = 2n ops

Purpose maxPos: n ops

Inner loop (comparison and purpose): 2 operations performed 2n ^ 2 times = 2n & sup2; OPS

Comparison of array elements (references to two arrays and comparison): 3n & sup2; OPS

Purpose of the new maxPos: n & sup2; OPS

Comparison of array elements (references to two arrays and comparison): 3n & sup2; OPS

Purpose and array reference: 2n & sup2; OPS

Purpose and 2 array references: 3n & sup2; OPS

Purpose and array reference: 2n & sup2; OPS

The total number of primitive operations

2n + n + 2n? + 3n? + n ^ 2 + 3n & sup2; + 2n? + 3n? + 2n? = 16n? + 3n

Reduction to Big Oh (n & sup2;)

? , ...

+3
2

, O (N 2) .

: , , " " , , ( ) - ( , ), big-O :

c n 0 , :

0 & le; f (n) & le; cg (n) n & ge; < > 0 > .

, 16N 2 + 3N n 0 c. , , c 16, n 0, -3 (, , 0, , ).

+2

( ) , , , , , , , .., , , , , . "j < i", "j ++" "numbers [i] = numbers [maxPos]", , - , . .

N ^ 2, .

+1

All Articles