简体   繁体   中英

Sorting Algorithm Explanation Complexity and Type

This is a sorting algorithm in Java. I have to analyze this algorithm but I'm really new to the subject and not sure about what each line does. I know that it's of the complexity of O(N²) but I don't understand what type it is.
Could someone please explain the method someAlgorithm() ?

This is the code:

import java.util.Arrays;

public class SomeClass {
    public static void main(String[ ] args) {
        int[] data = {12, 14, 13, 15, 19, 17, 16, 11, 18, 20};
        System.out.println("Compute some result for the Array : " + Arrays.toString(data));
        int[] result = someAlgorithm(data);
        System.out.println("Resulting Array: " + Arrays.toString(result));
    }
 
    private static int[] someAlgorithm(int[] data) {
        int size = data.length;
        int[] result = new int[size];
        for (int i = 0; i < size; i++) {
            int total = 0;
            for (int j = 0; j <= i; j++) {
                total += data[j];
            }
            int average = total / (i + 1);
            result[i] = average;
            System.out.println("Average for iteration " +  i + " is: " + average);
        }
        return result;
    }
}

The gist of the method someAlgorithm() is that it takes an array data as input and creates another array result of the same size, where result[i] stores the average (as an int ) of the first i elements of the input array.

Note that you can keep a running sum of the elements seen so far and reduce the complexity of this algorithm to O(N) fairly easily.

Also, as @Alex mentioned in the comments, this really has nothing to do with sorting and is not a type of sorting algorithm.

There are two types of algorithmic complexity :

  1. Space Complexity
  2. Time Complexity

As you said, this algorithm runs in O(N²) , and this is in regards to time complexity . This is because the time the algorithm will take to run increases with the square of the size variable. As for space complexity , it runs in O(N) , as the space (that is, the amount of memory) it takes up increases linearly with the size variable.

To see which time complexity an algorithm runs in, you need to look at how many nested loops there are, and how long they run for depending on the input.

To see which space complexity an algorithm runs in, you need to look at when and where data is stored, and how much of it is stored depending on the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM