Find duplicate element using Sorting approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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