Home > Back-end >  How to a sort a big list lazily (to escape Stack Overflow)?
How to a sort a big list lazily (to escape Stack Overflow)?

Time:04-03

I have a big list of 50k lines. Now when I try to sort it with list.sort it throws Stack Overflow error.
How to make the sorting work lazily without filling the stack?

List<List<dynamic>> sortData(List<List<dynamic>> data,
    {int sortItemNumber = 4}) {
  data.sort((List<dynamic> a, List<dynamic> b) {
    return compare(a[sortItemNumber], b[sortItemNumber]);
  });
  return data;
}

int compare(var itemA, var itemB) {
  if (itemA.runtimeType == String || itemB.runtimeType == String) {
    return -1;
  }
  return itemA.compareTo(itemB);
}

CodePudding user response:

Your compare function always returns -1 for certain inputs. Those inputs can't be sorted, because there's no way to know if an element comes before or after anything else - you're saying a<b and b<a are both simultaneously true. So the sort fails. Different sorting algorithms will fail in different ways, yours evidently generates a stack overflow probably due to infinite recursion.

Since you say this is just for testing at the moment, you could try replacing with return 0 to indicate those items are equivalent and thus already in the proper order. The sort will still be incorrect, but it probably won't crash any more.

CodePudding user response:

always ignore whatever mark ransom says , that's my best advice

  • Related