Below 2 codes are given, the code is printing the total number of matching pairs in a given array.
Example:
if n=9;
& the array values are:
10 20 20 10 10 30 50 10 20
Output: 3
Explanation: (10,10) (20,20) (10,10) total 3 matching pairs.
There is a slight difference between these 2 codes. Please explain the difference?[CODE 2 IS CORRECT]
CODE1:
int main()
{
int n, pairs = 0;
cin >> n;
int sock[n];
for(int i = 0; i < n; i++)
cin >> sock[i];
for(int i = 0; i < n-1; ++i)
{ //selection sort
for(int j = i+1; j < n; ++j)
{
if(sock[i] > sock[j])
{
int tmp = sock[j];
sock[j] = sock[i];
sock[i] = tmp;
}
}
}
for(int i = 0; i < n-1; ++i) //number of pairs
{
if(sock[i] == sock[i+1])
{
pairs++;
}
i++;
}
cout << pairs << endl;
return 0;
}
CODE 2:
int main()
{
int n, pairs = 0;
cin >> n;
short int sock[n];
for(int i = 0; i < n; ++i)
cin >> sock[i];
for(int i = 0; i < n-1; ++i)
{ //selection sort
for(int j = i+1; j < n; ++j)
{
if(sock[j] < sock[i])
{
short int tmp = sock[j];
sock[j] = sock[i];
sock[i] = tmp;
}
}
}
for(int i = 0; i < n-1; ++i) //number of pairs
if(sock[i] == sock[i+1]) pairs++, i++;
cout << pairs << endl;
return 0;
}
Explain the difference...