# Sorting An Array

Page 1 of 1

## 14 Replies - 5574 Views - Last Post: 27 August 2010 - 12:18 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=187551&amp;s=b4fe4fa28b993b8fad2190bcd4737bca&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 C#Coder12345

Reputation: 0
• Posts: 4
• Joined: 24-August 10

# Sorting An Array

Posted 24 August 2010 - 06:43 AM

Hi, Im a beginner in c# programming, and have a question.
I wrote a selection sort algorithm that sorts a one dimensional array(code below)...It works fine.

I would like to know can I use it on a two dimensional array?....Use selection sort algorithm to sort numbers in a two dimensional array.

Example: Random Numbers
6 8 4 11 15
5 2 7 9 10
13 14 12 1 3

Result should be:
sorted
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

``` private void SelectionSort(int[] LocalList)
{

for (int i = 0; i < LocalList.GetUpperBound(0); i++)
{
int minValue = i;

for (int j = i + 1; j < LocalList.GetUpperBound(0); j++)
{

if (LocalList[j] < LocalList[minValue])
{
minValue = j;
}
if (minValue != i)
{
SelectionSwap(LocalList, i, minValue);

}
}
}

```

```private void SwapFunction(int[] LocalList, int value, int minIndex)
{
int tempValue = LocalList[value];
LocalList[value] = LocalList[minIndex];
LocalList[minIndex] = tempValue;
}

```

Thanks

Is This A Good Question/Topic? 0

## Replies To: Sorting An Array

### #2 PennyBoki

• system("revolution");

Reputation: 53
• Posts: 2,335
• Joined: 11-December 06

## Re: Sorting An Array

Posted 24 August 2010 - 07:01 AM

Well, one way is transform the 2D array into 1D array. Then just you the same sorting algorithm, then transform again the 1D into 2D array and that's it.

### #3 Robin19

Reputation: 272
• Posts: 552
• Joined: 07-July 10

## Re: Sorting An Array

Posted 24 August 2010 - 08:52 AM

C#Coder12345, on 24 August 2010 - 05:43 AM, said:

Hi, Im a beginner in c# programming, and have a question.
I wrote a selection sort algorithm that sorts a one dimensional array(code below)...It works fine.

You might want to check your one dimensional array sort. I followed Penny's idea, copying your sort. I had to tweak the sort to make it come out correctly.

### #4 C#Coder12345

Reputation: 0
• Posts: 4
• Joined: 24-August 10

## Re: Sorting An Array

Posted 24 August 2010 - 10:03 AM

PennyBoki, on 24 August 2010 - 06:01 AM, said:

Well, one way is transform the 2D array into 1D array. Then just you the same sorting algorithm, then transform again the 1D into 2D array and that's it.

That is one way of doing it. Im not that familiar with two dimensional arrays thats why im using this example to help me out.
Im thinking of using the selection sort directly on the two dimensional array then transforming it to the 1D array. It it possible?

Thanks

### #5 fixo

• D.I.C Regular

Reputation: 85
• Posts: 335
• Joined: 10-May 09

## Re: Sorting An Array

Posted 24 August 2010 - 01:48 PM

C#Coder12345, on 24 August 2010 - 09:03 AM, said:

PennyBoki, on 24 August 2010 - 06:01 AM, said:

Well, one way is transform the 2D array into 1D array. Then just you the same sorting algorithm, then transform again the 1D into 2D array and that's it.

That is one way of doing it. Im not that familiar with two dimensional arrays thats why im using this example to help me out.
Im thinking of using the selection sort directly on the two dimensional array then transforming it to the 1D array. It it possible?

Thanks

Try this code snippet (using LINQ)
```            List<int[]> lst = new List<int[]>{
new int[]{6, 8, 4, 11, 15},
new int[]{5, 2, 7, 9, 10},
new int[] { 13, 14, 12, 1, 3 }
};

List<int[]> newlst = new List<int[]>();
foreach (int[] item in lst)
{
var sorted = from num in item
orderby num //sort by ascending (by default) otherwise use: < orderby num descending >
select num;

}
var lists = from list in newlst
orderby list[0]
select list;
newlst = new List<int[]>();
foreach (int[] item in lists)
{
}

foreach (int[] item in newlst)
{
foreach (int i in item)
{
Console.WriteLine(i);
}
Console.WriteLine("======================");
}
```

Ignore my code above try this one instead:

```            List<int[]> lst = new List<int[]>{
new int[]{6, 8, 4, 11, 15},
new int[]{5, 2, 7, 9, 10},
new int[] { 13, 14, 12, 1, 3 }
};

List<int[]> newlst = new List<int[]>();

List<int> tmp = new List<int>();

foreach (int[] item in lst)
{
foreach (int i in item)
{
}
}
tmp.Sort();
int count = lst[0].Length;
int c = 0;
for (int i = 0; i < tmp.Count; i += count)
{
int[] sublst = new int[count];
for (int j = 0; j < count; j++)
{
sublst[j] = tmp[c];
c += 1;
}

}

foreach (int[] a in newlst)
{
foreach (int b in a)
{
Console.WriteLine("{0}", B)/>;
}
Console.WriteLine("____________________________");
}
```

~'J'~

This post has been edited by fixo: 24 August 2010 - 03:53 PM

### #6 Curtis Rutland

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

Reputation: 4861
• Posts: 8,692
• Joined: 08-June 10

## Re: Sorting An Array

Posted 24 August 2010 - 02:09 PM

That algorithm simply doesn't work, fixo. That sorts each individual subarray, but the OP asked about sorting the entire matrix from top left to bottom right. Look at your output, and the output the OP asked for.

### #7 Curtis Rutland

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

Reputation: 4861
• Posts: 8,692
• Joined: 08-June 10

## Re: Sorting An Array

Posted 24 August 2010 - 02:09 PM

Ugh, double post.

This post has been edited by insertAlias: 24 August 2010 - 02:12 PM

### #8 fixo

• D.I.C Regular

Reputation: 85
• Posts: 335
• Joined: 10-May 09

## Re: Sorting An Array

Posted 24 August 2010 - 03:08 PM

insertAlias, on 24 August 2010 - 01:09 PM, said:

That algorithm simply doesn't work, fixo. That sorts each individual subarray, but the OP asked about sorting the entire matrix from top left to bottom right. Look at your output, and the output the OP asked for.

Oops,
I haven't noticed that it is necessary to sort all elements inside
through the whole massive, so ignore my post
Regards,

~'J'~

### #9 Bixel

Reputation: -1
• Posts: 29
• Joined: 20-August 10

## Re: Sorting An Array

Posted 24 August 2010 - 10:15 PM

would this work?

```int[] myArray = {13, 14, 12, 1, 3};

Array.Sort(myArray);

```

or does that only do alphabetical?

This post has been edited by Bixel: 24 August 2010 - 10:16 PM

### #10 C#Coder12345

Reputation: 0
• Posts: 4
• Joined: 24-August 10

## Re: Sorting An Array

Posted 24 August 2010 - 10:29 PM

Bixel, on 24 August 2010 - 09:15 PM, said:

would this work?

```int[] myArray = {13, 14, 12, 1, 3};

Array.Sort(myArray);

```

or does that only do alphabetical?

I don't think it uses selection sort though.

### #11 janne_panne

• WinRT Dev

Reputation: 428
• Posts: 1,047
• Joined: 09-June 09

## Re: Sorting An Array

Posted 25 August 2010 - 12:34 AM

It's not that hard to modify one-dimensional array selection sort to two-dimensional: You just search for the smallest element and swap it.

This method searches the smallest number in 2d array:

```        private static void FindSmallest(int[][] array)
{
int smallest = int.MaxValue;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
int num = array[i][j];
if (num < smallest)
{
smallest = num;
}
}
}
}

```

The only slight problem might the return value. What should that method return? How about our own Location class which tells where the smallest number is:

```        class Location
{
public int Row { get; set; }
public int Cell { get; set; }
public int Value { get; set; }
}

private static Location FindSmallest(int[][] array)
{
Location location = new Location();
int smallest = int.MaxValue;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
int num = array[i][j];
if (num < smallest)
{
smallest = num;
location.Row = i;
location.Cell = j;
location.Value = num;
}
}
}
return location;
}

```

Next just a Sort method which finds the smallest elements and swaps them:

```        private static void Sort(int[][] array)
{
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
Location smallest = FindSmallest(array, elements);
// swap
}
}
}

```

That's a start. I won't give all the code immediatly, where is the fun in that. I hope this helps you to understand the 2d arrays a bit better and you end up with succesful sort program. If you can't figure out what's needed, of course we will help you further but think by yourself first.

### #12 fixo

• D.I.C Regular

Reputation: 85
• Posts: 335
• Joined: 10-May 09

## Re: Sorting An Array

Posted 25 August 2010 - 03:30 AM

I prefer use List instead of multidimensional array
Here is another way using SortedList

```            List<int[]> lst = new List<int[]>{
new int[]{6, 8, 4, 11, 15},
new int[]{5, 2, 7, 9, 10},
new int[] { 13, 14, 12, 1, 3 }
};

List<int[]> newlst = new List<int[]>();

SortedList sorted = new SortedList();

foreach (int[] item in lst)
{
foreach (int i in item)
{
}
}
int cnt = lst[0].Length;

int pos = 0;

for (int i = 0; i < sorted.Count; i += cnt)
{
int[] sublst = new int[cnt];

for (int j = 0; j < cnt; j++)
{
sublst[j] = (int)sorted.GetByIndex(pos);
pos += 1;
}

}
foreach (int[] a in newlst)
{
string s = String.Empty;

foreach (int b in a)
{
s = s + b.ToString() +"\t";
}
Console.WriteLine("{0}", s);
}
```

~'J'~

### #13 Curtis Rutland

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

Reputation: 4861
• Posts: 8,692
• Joined: 08-June 10

## Re: Sorting An Array

Posted 25 August 2010 - 09:43 AM

C#Coder12345, on 25 August 2010 - 04:29 AM, said:

Bixel, on 24 August 2010 - 09:15 PM, said:

would this work?

```int[] myArray = {13, 14, 12, 1, 3};

Array.Sort(myArray);

```

or does that only do alphabetical?

I don't think it uses selection sort though.

It doesn't. Array.Sort uses the quicksort algorithm. Typically much more efficient than the selection sort. I believe Enumerable.OrderBy also uses this kind of sort.

Learning these sorting algorithms is nice, but realistically, you'll never have to use them in C#, because the built in sorts are more efficient than all of the O(n2) sorts textbooks teach.

### #14 C#Coder12345

Reputation: 0
• Posts: 4
• Joined: 24-August 10

## Re: Sorting An Array

Posted 26 August 2010 - 09:57 AM

janne_panne, on 24 August 2010 - 11:34 PM, said:

It's not that hard to modify one-dimensional array selection sort to two-dimensional: You just search for the smallest element and swap it.

The only slight problem might the return value. What should that method return? How about our own Location class which tells where the smallest number is:

```        class Location
{
public int Row { get; set; }
public int Cell { get; set; }
public int Value { get; set; }
}

private static Location FindSmallest(int[][] array)
{
Location location = new Location();
int smallest = int.MaxValue;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
int num = array[i][j];
if (num < smallest)
{
smallest = num;
location.Row = i;
location.Cell = j;
location.Value = num;
}
}
}
return location;
}

```

That's a start. I won't give all the code immediatly, where is the fun in that. I hope this helps you to understand the 2d arrays a bit better and you end up with succesful sort program. If you can't figure out what's needed, of course we will help you further but think by yourself first.

Is there a way without using any classes as im not familiar with it yet?..Could I perhaps use this as a function on its own?

Thanks

### #15 janne_panne

• WinRT Dev

Reputation: 428
• Posts: 1,047
• Joined: 09-June 09

## Re: Sorting An Array

Posted 27 August 2010 - 12:18 AM

Yes, it is possible without classes. With class it's just easier to return multiple values (row, cell and value information). But without class you could return an array of integer with those three values in cells. Or you could use reference parameter.

http://msdn.microsof...28VS.71%29.aspx

Sample with int[]:
```
/// <summary>
/// Returns the smallest value of the 2d array
/// <para>int[0] = row</para>
/// <para>int[1] = cell</para>
/// <para>int[2] = value</para>
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
private static int[] FindSmallest(int[][] array)
{
int[] returnValue = new int[3];
int smallest = int.MaxValue;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
int num = array[i][j];
if (num < smallest)
{
smallest = num;
returnValue[0] = i;
returnValue[1] = j;
returnValue[2] = num;
}
}
}
return returnValue;
}

```

sample with ref parameters:
```        public static void main()
{
int[][] arr = new int[][] {
new int[] {4,6,9},
new int[] {2,3,1}
};

int row = -1;
int cell = -1;
int value = int.MaxValue;
FindSmallest(arr, ref row, ref cell, ref value);
Console.WriteLine("row: " + row);
Console.WriteLine("cell: " + cell);
Console.WriteLine("value: " + value);
}

private static void FindSmallest(int[][] array, ref int row, ref int cell, ref int value)
{
int smallest = int.MaxValue;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
int num = array[i][j];
if (num < smallest)
{
smallest = num;
row = i;
cell = j;
value = num;
}
}
}
}

```