# Fastest Way to Sort a 2 Dimensional Array

• (2 Pages)
• 1
• 2

## 22 Replies - 15053 Views - Last Post: 16 January 2014 - 09:12 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=337961&amp;s=73e7cb956cfe3252878c09a05ff3528b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

# Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 12:29 PM

Here is what I have, I have a 1D Array being added to a 2D Array and I need to Sort them by value value 3 in the 2D Array
while maintaining a specific amount.

Here is what I have so far:
``` public static void CheckHS(string[] HS)
{

try
{
GeneralData.HighScores[10, 0] = "11";
GeneralData.HighScores[10, 1] = HS[1];
GeneralData.HighScores[10, 2] = HS[2];
GeneralData.HighScores[10, 3] = HS[3];

//Need Sort Data - Bubble Sort?

}//end Try
catch (Exception ex) { MessageBox.Show(ex.Message); }
}

```

I am thinking bubble sorting but I remember reading about something faster. Unfortunately I can't find it on the web. The idea is that there will be always 10 Values and 4 Columns on the 2D Array. [The 11th Row being empty at the end of it.
Any Ideas?

Is This A Good Question/Topic? 0

## Replies To: Fastest Way to Sort a 2 Dimensional Array

### #2 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 12:51 PM

Updated Coding
``` public static void CheckHS(string[] HS)
{
string[] temp = new string[4];
try
{
for (int x = 0; x <= GeneralData.HighScores.GetUpperBound(0); x++)
{
if (GeneralData.HighScores[x,1] != String.Empty )
{
if (Convert.ToDouble(GeneralData.HighScores[x, 3]) <= Convert.ToDouble(HS[3]))
{
if (Convert.ToDouble(GeneralData.HighScores[x, 3]) < Convert.ToDouble(HS[3]))
{
temp[1] = GeneralData.HighScores[x, 1];
temp[2] = GeneralData.HighScores[x, 2];
temp[3] = GeneralData.HighScores[x, 3];
GeneralData.HighScores[x, 1] = HS[1];
GeneralData.HighScores[x, 2] = HS[2];
GeneralData.HighScores[x, 3] = HS[3];
HS[1] = temp[1];
HS[1] = temp[2];
HS[1] = temp[3];
x = -1;
}
else
{
DateTime oldDate = Convert.ToDateTime (HighScores[x,1]);
DateTime newDate = Convert.ToDateTime(HS[1]);
TimeSpan ts = newDate - oldDate;
int diff = ts.Days;
if (diff >0)
{
temp[1] = GeneralData.HighScores[x, 1];
temp[2] = GeneralData.HighScores[x, 2];
temp[3] = GeneralData.HighScores[x, 3];
GeneralData.HighScores[x, 1] = HS[1];
GeneralData.HighScores[x, 2] = HS[2];
GeneralData.HighScores[x, 3] = HS[3];
HS[1] = temp[1];
HS[1] = temp[2];
HS[1] = temp[3];
x = -1;
}
}
}
}
else
{
GeneralData.HighScores[x, 1] = HS[1];
GeneralData.HighScores[x, 2] = HS[2];
GeneralData.HighScores[x, 3] = HS[3];
break;
}
}
//Now Create Numerics and Clear out 10
for (int x = 1; x <= GeneralData.HighScores.GetUpperBound(0); x++)
{
if (x != 10)
{
GeneralData.HighScores[x, 0] = x.ToString();
}
else
{
GeneralData.HighScores[x, 0] = string.Empty;
GeneralData.HighScores[x, 1] = string.Empty;
GeneralData.HighScores[x, 2] = string.Empty;
GeneralData.HighScores[x, 3] = string.Empty;
}
}
}//end Try
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { Array.Clear(temp, 0, temp.Length); }
}

```

This post has been edited by alapee: 09 January 2014 - 12:51 PM

### #3 andrewsw

• RequestedRangeNotSatisfiable

Reputation: 6552
• Posts: 26,565
• Joined: 12-December 12

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 12:52 PM

Quote

I am thinking bubble sorting but I remember reading about something faster.

Did you search "sorting" ? wiki

Here is an SO topic including code, and a suggestion to use a DataTable.

An additional question: Do you actually need to sort the array? But I'll assume that you do.

### #4 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 12:55 PM

Andrew you must have posted, right as I was updating the Code with a post

Interesting, I have see the SO Sort before but that is not what I was thinking. I will check the other link out more in detail

### #5 andrewsw

• RequestedRangeNotSatisfiable

Reputation: 6552
• Posts: 26,565
• Joined: 12-December 12

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 12:56 PM

BTW Your array is very small, so I wouldn't bother attempting to use the fastest sorting method. I wouldn't use bubble-sort, but I would use one that I could understand (preferably..).

Edited: Actually, I'm lying. I would find code, possibly for quicksort, use and test it thoroughly.. and not care if I don't fully understand it

This post has been edited by andrewsw: 09 January 2014 - 12:59 PM

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 01:04 PM

It be simple to a create a class.

```Class Score
Score : Integer
Name  : String

Scores[] : Score

HighScoreTable = From s In Scores OrderBy s.Score Descending

```

This post has been edited by AdamSpeight2008: 09 January 2014 - 01:06 PM

### #7 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 01:08 PM

There is an orderby in C#? I have to look this up now.

### #8 Curtis Rutland

• （╯°□°）╯︵ (~ .o.)~

Reputation: 5103
• Posts: 9,283
• Joined: 08-June 10

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 01:54 PM

It's part of LINQ, a collection querying API. That's why you don't usually see multi-dimension arrays in C#, because it makes more sense to build a class and make a collection of instances of that class. The tools to manipulate them are much more fluent. In fact, I've never once needed parallel or multidimensioned arrays in C#.

It's an OOP thing.

### #9 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 02:21 PM

I am starting see that about 2D + Arrays in C#. This last 2 months has been getting me reacquainted with C#. I have still yet to bust into XML side of it, not to mention barely touching the Graphics Abilities.

### #10 baavgai

• Dreaming Coder

Reputation: 7183
• Posts: 14,970
• Joined: 16-October 07

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 02:40 PM

The use of a 2D array when each dimension has meaning, like a game board or map, makes sense.

However, if you only employ your extra dimension to essentially create data columns for rows of data, then you're doing it wrong.

Look at AdamSpeight2008's response. Ask yourself why you need a 2D array; then use a class.

### #11 andrewsw

• RequestedRangeNotSatisfiable

Reputation: 6552
• Posts: 26,565
• Joined: 12-December 12

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 02:47 PM

baavgai, on 09 January 2014 - 09:40 PM, said:

The use of a 2D array when each dimension has meaning, like a game board or map, makes sense.

I like this thought.
It made me think.. if you can switch x and y throughout and the program still works then an array is suitable. Does this sound right?

### #12 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 03:16 PM

baavgai, on 09 January 2014 - 03:40 PM, said:

The use of a 2D array when each dimension has meaning, like a game board or map, makes sense.

However, if you only employ your extra dimension to essentially create data columns for rows of data, then you're doing it wrong.

Look at AdamSpeight2008's response. Ask yourself why you need a 2D array; then use a class.

I was taking Adam's thought and spinning very carefully. I like this view point of a 2D Array also.
After All the grande thing about using C# is the ability to make classes.

andrewsw, on 09 January 2014 - 03:47 PM, said:

baavgai, on 09 January 2014 - 09:40 PM, said:

The use of a 2D array when each dimension has meaning, like a game board or map, makes sense.

I like this thought.
It made me think.. if you can switch x and y throughout and the program still works then an array is suitable. Does this sound right?

Yes, it sounds correct. Looks like I am still stepping out of my VB habits.

### #13 Curtis Rutland

• （╯°□°）╯︵ (~ .o.)~

Reputation: 5103
• Posts: 9,283
• Joined: 08-June 10

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 03:38 PM

Well, on top of just making classes, you can query and sort the collection. Let's say you had a class defined like this:

```public class HighScore
{
public string Name {get;set;}
public int Points {get;set;}
}
```

And let's say we have some method called GetHighScores that returns a List<HighScore>. You could then do cool stuff like this:

```var allHighScores = GetHighScores();
var scoresWeWant = from score in allHighScores
where score.Points > 100
orderby score.Points descending
select score;

```

And now you have a collection that has only high scores greater than 100, and ordered descending by points. Or you could do something a bit dofferent:

```var allHighScores = GetHighScores();
var scoresWeWant = allHighScores.OrderByDescending(score => score.Points).Take(10);
```

Now we've sorted it the same way, but instead of filtering on a particular number, we're only taking the top 10 scores.

It's extremely flexible. Also, you'll recognize a lot of operators if you have any SQL experience. BTW, the first is an example of LINQ's query syntax, and the second is an example of the Extension Methods that the query syntax is "sugar" for.

### #14 alapee

• Stressed Out Programmer

Reputation: 214
• Posts: 2,464
• Joined: 24-October 13

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 03:44 PM

Yeah I see the similarities with the SQL. I didn't know you could orderby let alone run base query. This some very interesting stuff.
I am still learning a lot of the shortcuts also.
I have been looking over alot of the tutorials and I am noticing that my coding is not quite matching up with theirs. Is there a tutorial/FAQ for good programming in C#? {I just might not have gotten to it yet}

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

## Re: Fastest Way to Sort a 2 Dimensional Array

Posted 09 January 2014 - 11:21 PM

Just an additional point to consider as well alapee. You are using the type String to contain the numerical score. Then doing sort on it.
The result wouldn't be the one you be expecting.

Let say the scores where
1 2 3 30 20 10
the result of the sort (assuming Ascending)
1 10 2 20 3 30
not
1 2 3 10 20 30

cos it'll do Alphabetical sort (aka Dictionary sorting). As the computer would treat the Score as text information (cos you told it to store it as a String). So it doesn't comprehend that text is actually a number.

Where as if you stored the Score value in a numeric type (eg Integer, Double, etc) it'll understand that this value is number.
So when you do an sort (or OrderBy) it'll do it in the way you expect, producing the result
1 2 3 10 20 30

Tutorial Suggestion:- Parallel Arrays, Array with Object (Class & Structure) (vb.net but conceptually still valid)

This post has been edited by AdamSpeight2008: 09 January 2014 - 11:25 PM