Okay, let's focus on this:
1 2 3 4 5 6
|
int n[] = { 1, 2, 2, 3 };
for(int i = 0; i < 3; i++)
for(int j = i + 1; j < 4; j++)
if(n[i] == n[j])
cout << n[i] << endl;
|
For clarity's sake, I have reduced the size of the array.
Let's picture this array as follows:
http://oi42.tinypic.com/29di7t2.jpg
Let
i be red and
j be blue. Then, this is the effect the loops achieve (highlighted squares denote a found duplicate):
http://oi40.tinypic.com/2qlev5i.jpg
Sorry for the links, but this forum apparently doesn't implement image tags.
Just for fun, notice that if
n is the size of the array, then this algorithm performs a total of
n * (n - 1) / 2 comparisons, thus rendering it an
O(n2) algorithm.
There are better alternatives. For example, if loop through the array and use a hash table to both store its elements and check for duplicates, then we'd end up with an
O(n) algorithm.