0

I have a linked list of elements with a texture index. They are unsorted. I need them sort them so that the texture index is ascending in order. I could always declare another list and read into that but I am curious about ways to sort in place. Anyone have a suggest or link of where I should start/what I should start looking for to do this? Also I am not using the STL list.

Thank you!

Juiceyboxers
  • 1
  • 1
  • 2
  • 1
    Why not use `std::list` instead of a custom list? (And of course, why use a list at all? It's arguably the worst container.) – GManNickG Apr 29 '11 at 01:40
  • First you'd need to explain what "in place" is supposed to mean when applied to linked list. Without generating another list? Without relinking elements of the existing list? Something else? – AnT stands with Russia Apr 29 '11 at 02:47

2 Answers2

2

Sorting a linked list is probably best served by mergesort (still O(n log n) even for a list) since you don't have random element access. If you can switch to std::list the list::sort function will take care of it for you.

Alternately use a non-list container instead of list and you can use any sort method you please.

Mark B
  • 95,107
  • 10
  • 109
  • 188
-1

Sorting a linked list in place is not so efficient because of the lack of random access. You could always use a simple algorithm like bubble sort if you know your list won't be very long, or perhaps if you can afford the small bit of extra complexity, insertion sort would be better.

An alternative method that is probably better than trying to sort a linked list is to just insert each new node in the right place, so that after adding an element the list is sorted.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249