The code you provided is attempting to remove duplicates from an array by shifting elements. However, there's an issue in the code that leads to incorrect results. The problem is with the inner loop where you're shifting the elements of the array. Let's break down what's happening:
- The initial array is: {1,2,3,4,4,5,6,6,7,7,8,8,9,9,10,11,11,12,12,13}.
- As you iterate through the array, you encounter the first duplicate at index 3 (value 4) and enter the inner loop to shift elements.
- After the inner loop completes, the array becomes: {1,2,3,4,5,6,6,7,7,8,8,9,9,10,11,11,12,12,13,13}.
- The next duplicate is encountered at index 6 (value 6), and you again enter the inner loop to shift elements.
- After this inner loop completes, the array becomes: {1,2,3,4,5,6,7,7,8,8,9,9,10,11,11,12,12,13,13,13}.
- The inner loop continues shifting elements for each encountered duplicate, which results in elements being shifted more than once, causing incorrect behavior and leading to an incorrect count of duplicates.
To fix this issue, you should use a different approach to remove duplicates from the array. One common approach is to use a secondary array to store unique elements as you iterate through the original array. Here's a modified version of your code that uses this approach:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,4,5,6,6,7,7,8,8,9,9,10,11,11,12,12,13};
int length = sizeof(arr)/sizeof(arr[0]);
int uniqueArr[length];
int uniqueCount = 0;
for(int i = 0 ; i < length ; i++)
{
bool isDuplicate = false;
for(int j = 0; j < uniqueCount; j++)
{
if(arr[i] == uniqueArr[j])
{
isDuplicate = true;
break;
}
}
if(!isDuplicate)
{
uniqueArr[uniqueCount] = arr[i];
uniqueCount++;
}
}
cout << "Number of duplicates: " << length - uniqueCount << endl;
cout << "Array after removing duplicates: ";
for(int i = 0 ; i < uniqueCount ; i++)
{
cout << uniqueArr[i] << " ";
}
return 0;
}