Find the third largest number without sort() method
// this the main() function of dart
void main() {
List<int> numbers = [10, 5, 8, 20, 15];
// Ensure the array has at least three elements
if (numbers.length < 3) {
print("Array should have at least three elements");
return;
}
int findThirdLargest(List<int> arr) {
int firstMax = arr.removeAt(arr.indexOf(arr.reduce((a, b) => a > b ? a : b)));
int secondMax = arr.removeAt(arr.indexOf(arr.reduce((a, b) => a > b ? a : b)));
int thirdMax = arr.reduce((a, b) => a > b ? a : b);
return thirdMax;
}
int thirdLargest = findThirdLargest(List.from(numbers));
print("The third largest number is: $thirdLargest");
}
Comments
Post a Comment