-
suck at sorting arrays
I have to arrays (which contents has a relation). One is filled with integers and the other is filled with string.
The string syntax is as follows "X_8","X_5", "X_3", "X_10" etc.
Both arrays need to be sorted numerically but compared to the string. So I need to get it sorted like:
"X_1","X_3",X_4","X_10" etc.
how do I do this
-
Okay, this is two seperate problems, both of which are good for young programmers to learn with.
First rule of this lesson is the same as the first rule for every lesson, there is always more than one way to do something.
First, let's look at how to sort on an array.
The method I suggest is start by making a new, empty array. Step through the source array from first element to last, or last to first, it doesn't matter. If you pop(), then you will be moving from last to first treating the array like a stack, and that is probably the way it is done most often.
Every time you get an element, you start at the end of the sorted array and compare it. If it is less than the current element of the sorted array, then you subtract one from your current index and move on. You keep comparing like this until you reach an element who's value is less than the value of the element you are looking to add to the sort.
When that happens, you shuffle everything you've just passed over, growing the array by one.
Let's say you were doing an alphabetical sort. You had Washington, Jefferson, Lincoln, and Hamilton.
You pull off Jefferson, and add it to the new sorted array.
Washington, Jefferson, Lincoln
Hamilton
You pull off Lincoln. You compare it to the last element, which is Jefferson. It is greater than the last element so it becomes the new last element.
Washington, Jefferson
Hamilton, Lincoln
You pull off Jefferson, you compare it to the last element. It is less than Lincoln, so you compare it to the next element. It is greater than Hamilton, so you will now add an empty slot to the array, shuffle down all the values, and insert Jefferson.
In steps it will look like this...
Hamilton, Lincoln
Hamilton, Lincoln, <empty>
Hamilton, Lincoln, Lincoln
Hamilton, Jefferson, Lincoln
This continues. Hopefully you see the logic pattern and you can sculpt the code around that.
As to the second problem, comparing values in an X_1 format. That depends on the language.
VB has a Split() funciton. You can split around the _ and just do your comparisions on the numbers.
Sorry if this is too terse, or too long. And sorry if I grossly misspelled anything (particularly Lincoln).