for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++){
//do swap stuff, constant time
}
}
I read that single for loop is O(N) a
As you mentioned
Each takes unit of 1 - O(1)
So each iteration of the inner loop takes 1, 2, 3, ... , n unit time.
total_time = 1 + 2 + 3 + ... + (n-2) + (n-1) + n
Reversing
total_time = n + (n-1) + (n-2) + ... + 3 + 2 + 1
Adding
2 * total_time = (n+1) + (n+1) + (n+1) + ... + (n+1) + (n+1) + (n+1)
There are total n terms
2 * total_time = (n+1) * n
=> total_time = (n+1) * n / 2
=> total_time = n^2 / 2 + n / 2
Lower terms and constant coefficients are neglected for big O complexity.
As a result
O(n^2)