Home > Enterprise >  Print the second largest number on the list using dart
Print the second largest number on the list using dart

Time:11-14

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);
    }
   }
  }
 }
}

CodePudding user response:

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);
}

CodePudding user response:

I need to print the second largest number on the list

  1. Sort the array (desc).
  2. Access the second element.
List a = [9, 6, 4, 10, 13, 2, 3, 5];

a.sort((a, z) => z - a);
// final b = a.toList()..sort(...); if you do not want to modify the original array.

print(a.take(2));         // [13, 10]
print(a.take(2)[1]);      // [10]
print(a.take(2).skip(1)); // [10]
print(a.skip(1).first);   // [10]

CodePudding user response:

You are missing () on sort. You can do

void main() {
  List a = [9, 6, 4, 10, 13, 2, 3, 5];
  a.sort();
  print(a[a.length - 2]); //get second large item

  List b = [9, 6, 4, 10, 13, 2, 3, 5];
  //or like revese sort
  b.sort((a, b) => b.compareTo(a));
  print(b[1]);
  
}

  • Related