Skip to content

Instantly share code, notes, and snippets.

Created February 24, 2021 16:05
What would you like to do?
Find duplicate element using Sorting approach
#include <bits/stdc++.h>
using namespace std;
int sorting_duplicate(int arr[], int n)
//Sort the array using STL sort function or write own sorting algorithm(merge sort or heap sort)
sort(arr, arr + n);
for (int i = 1; i < n; i++)
//As the list is sorted,if two consecutive values are found, return the value as it is duplicate
if (arr[i] == arr[i + 1])
return arr[i];
// If duplicate value is not found, return -1
return -1;
// Driver Code
int main()
//Create an array with 1 duplicate value
int arr[7] = {1, 2, 3, 9, 3, 6, 5};
//Calculate size of array
int n = sizeof(arr) / sizeof(arr[0]);
//Find out either the duplicate element present in the array or -1
int duplicate = sorting duplicate(arr, n);
//Print duplicate array element
cout << duplicate << endl;
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment