Sorting a list of integers

  • Thread starter Thread starter robin9876
  • Start date Start date
R

robin9876

I have a list of integers (example sub set of data below), what is the
best method of sorting these in code?

1, 872
5, 1283
8, 343
9, 123
 
Bubble sort is O(n^2), isn't it? I'm not sure how Array.Sort is
implemented, but it's probably better than O(n^2).
To OP, put the numbers into an array and then call Array.Sort.

I'd use Array.Sort as well. It uses the quicksort algorithm so it's
faster and most importantly it's already implemented for us.
 
I thought that the array list option only allows one value to be set in
the array and still allowed to be sorted?
 
I thought that the array list option only allows one value to be set in
the array and still allowed to be sorted?

You mean does it have to contain unique values? No. Array.Sort makes no such
requirement.
 
I mean if the rows have two values but then sorting on one of the
columns and not an amalgamation of the columns.
 
Don't mean to toot my own horn... but I took a list at code referenced at
that link and frankly I wouldn't do it that way. For a couple of reasons
but in so far as I can tell by just reading the code it may not work
properly. Not saying it "doesn't" just that it might not.

Why? Because the QuickSort used in .Net is not a "stable sort". That means
that subsequent sorts of the same data are not guaranteed to maintain order
when two items are identical (i.e. already sorted.) A stable sort algorithm
wouldn't move two items if they are equal and a non-stable sort algorithm
would (and does). It gains speed this way but the result is if you sort one
column and then sort another column the first sort can change making them
unsorted again. It could be that the fellow accomodates this in his code
but I couldn't see it.

What I did to solve it (some years ago) is introduce a stable sort option
which insures that multiple calls maintain earlier sorts. Instead of having
to pass an array of values or run it through a special routine you simply
ask for something along the lines of: object.SortStable( item ) on as many
items as you want.

The code would have to be adapted a bit but if anybody is interested you
should be able to find it here: http://www.searchcsla.com/Search.aspx where
it was archived. Enter "Sort" for the search criteria and you'll see a
couple of threads including "Stable Sort Solved" which is where I posted the
code.

Seems a shame to have the code go to waste if somebody can use it.

Tom
 
Back
Top