I need help to check whether my ascending sorting code has correct time complexity measurement or not.
Here is my code
for (int i = 0; i < 4344; i++)
{
for (int j = i + 1; j < 4344; j++)
{
if (array_dist[index_arr[i]] > array_dist[index_arr[j]])
{
x = index_arr[i];
index_arr[i] = index_arr[j];
index_arr[j] = x;
}
}
}
We have two nested loops so N^2 and if statement with 3 operations, so N^2 + 3 then we got O(N^2).
I am not sure if O(N^2) is the correct time complexity for my code. I want to know if the if statement could change my answer?
ifcondition is always true?O(1)since the runtime isn't dependent on the length of the input (N). (It's always 4344)ifis irrelevant here since the content of theifblock isO(1). The number of time you execute the inner loop isO(n^2)(assuming you do not have constant bound), regardless of whether you enter theifor not. Entering theifor not (all the time) only multiply thisn^2by a constant, so that's stillO(n^2).O(N^2).N^2 * 3(times, not plus), because for every loop you execute 3 operations (assuming you always enter theif), butO(3 * N^2)isO(N^2).