Learn-dsa..in 30 days!



























CC-16 : Demonstrate natural sorting using a TreeSet.

Description:

Given a double array arr as input, add its elements to a TreeSet to demonstrate natural sorting using a TreeSet.

Test cases and expected outputs:

Input Parameters Expected outputs
arr1[]={ 1.0, 4.6, 8.1, 3.7, 4.60, 1, 3.4, 9.5}; Sorted Elements : 1.0,3.4,3.7,4.6,8.1,9.5
arr1[]={ 7.2, 8.0, 5,3}; Sorted Elements : 3.0,5.0,7.2,8.0

Pseudocode:

The java method should accept following input parameters: arr (double array).
Initialize a variable set of type TreeSet to hold the input elements.
Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr1.length-1:
Add arr1[idx] to set1.
After the loop completes the double elements of arr have been sorted in ascending order in set.
Initialize a double array retval with size same as set.size().
Use an iterator to access elements from set and add the same to int array retVal. Return retVal.

Code:

public double[] setArrayTreeHash(double[] arr) {
	TreeSet<Double> set=new TreeSet<Double>();
	for (int idx=0; idx < arr.length; idx++) {
		set.add(arr[idx]);
	}
	double retVal[]=new double[set.size()];
	int idx=0;
	Iterator<Double> itr=set.iterator();
	while (itr.hasNext()) {
		retVal[idx]=itr.next().doubleValue();
		idx++;
	}
	return retVal;
}

Click here to download and run code and test cases !