I got this formula from a data structure book in the bubble sort algorithm.
(N-1) + (N-2) +...+ 2 + 1
is a sum of N-1 items. Now reorder the items so, that after the first comes the last, then the second, then the second to last, i.e.(N-1) + 1 + (N-2) + 2 +...
The way the items are ordered now you can see that each of those pairs is equal to N ie (N-1+1 is N, N-2+2 is N)
. Since there are N-1 items, there are (N-1)/2
such pairs. So you're adding N (N-1)/2
times, so the total value is N*(N-1)/2.
Now let me explain with an example
if n = 5
(5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 5(5 - 1)/2
4 + 3 + 2 + 1 = 5(4)/2
10 = 10
Now reorder the items so, that after the first comes the last, then the second, then the second to last4 + 1 = 5, 3 + 2 = 5
Since there are N-1 items(5 - 1) + (5 - 2) + (5 - 3) + (5 - 4)
there are (N-1)/2
such pairs (5 - 1)/2 = 2
(4 + 1 = 5), (3 + 2 = 5)
So you're adding N (N-1)/2
times
ie add N 2 times5 + 5 = 10