Print the second largest number on the list using dart

Issue

I need to print the second largest number on the list,
the output from the below code is all elements in the list except the first and the last one.
What is the mistake?

void main () {
List a = [9,6,4,10,13,2,3,5];
 a.sort;
 for(int x in a){
  for (int max in a){
   for (int second_last in a){
    if (x > max) {
    second_last = max;
    max = x;
    } else if (x > second_last && x != max) {
      second_last = x;
      print(second_last);
    }
   }
  }
 }
}

Solution

There are a few things wrong with your code:

  1. You’re not actually sorting the list. The sort method returns a new sorted list, it doesn’t sort the existing list. So you need to do:
a = a.sort;
  1. You’re iterating over the list 3 times when you only need to iterate over it once.

  2. You’re not keeping track of the second largest number, you’re just printing it out as you find it.

  3. You’re not checking for duplicates. If there are duplicate numbers in the list, your code will print them out multiple times.

Here’s a corrected pseudo-code

void main() {
  List a = [9, 6, 4, 10, 13, 2, 3, 5];
  a = a.sort;
  int max = a[0];
  int second_last = a[1];
  for (int x in a) {
    if (x > max) {
      second_last = max;
      max = x;
    } else if (x > second_last && x != max) {
      second_last = x;
    }
  }
  print(second_last);
}

Answered By – Igor

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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