Print sorted unique elements of a given array

Objective: Given an array of integers with duplicates, write a program to print unique elements in the array in sorted order.

Example:

Given Input: [6, 1, 8, 5, 2, 10, 17, 25, 6, 5, 1, 8, 8]
Sorted Distinct Elements: 1 2 5 6 8 10 17 25 

Given Input: [2, 2, 2, 2]
Sorted Distinct Elements: 2

Approach: Use Tree Set

Set maintains unique elements and tree set maintains unique elements in sorted order. So insert all the elements of input array to the tree set and then print the set.

Complete Code:

Output:

Given Input: [6, 1, 8, 5, 2, 10, 17, 25, 6, 5, 1, 8, 8]
Sorted Distinct Elements: 1 2 5 6 8 10 17 25

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: