How to calculate the running time of an algorithm

I am trying to improve my knowledge in Algorithms, and I was wondering if anyone could give me a good explanation of how easy it is to calculate the running time.

boolean hasDuplicate(int[] array) {
    for (int i = 0; i < array.length; i++) {
       for (int j = 0; j < array.length; j++) {
            if (array[i] == array[j] && i != j) {
                return true;
            }
       }
    }
    return false;
}

So he says: This array takes O (n 2 ) runtime because each element must be associated with n elements (where n is the length of the array). Therefore, if we double the inputs, we will quadruple the time.

Question:

Let's say the array was [1,2,3], and if we double it [1,2,3,4,5,6], how to do it four times? Shouldn't it be twice the work time?

+4
source share
5 answers

if array.length * array.length . O(N^2), N .

+1

- for ( , ?)

, n. n 2 ( , ?). 2n, (2n) 2= 4n 2. , , , . , , .

, , .

, !

0

n . , :

for (int i = 0; i < array.length; i++) {
   for (int j = 0; j < array.length; j++) {
        if (array[i] == array[j] && i != j) {
            return true;
        }
   }
}

i 0 n-1. n .

i j 0 n-1.

, n = 5.

i = 0  j <-- 0,1,2,3,4
i = 1  j <-- 0,1,2,3,4
i = 2  j <-- 0,1,2,3,4
i = 3  j <-- 0,1,2,3,4
i = 4  j <-- 0,1,2,3,4

, 5 x 5 = 25 times. n-squared times.

0

, , : , . compareTo, , , . :

  • O (n ^ 2) K, 2K, 3K, 4K . .
  • 1, O (n log n).

, , .

0

, [1,2,3]

        if (array[i] == array[j] && i != j) {
            return true;
        }

3 * 3 = 9 , [1,2,3,4,5,6], 6 * 6 = 36 . , (36/9 = 4).

, N, if N * N , O (N ^ 2).

0

All Articles