Sorting an array in C# except one number
Firstly this is my code:
int[] a = { 3, 2, 0, 4, -5, 8, 7, 6 };
Array.Sort(a);
for(int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
Output:
-5
0
2
3
4
6
7
8
My problem is that I want to sort all the numbers like the computer already does, but except the -5. This is what I want the output to be:
0
2
3
4
-5
6
7
8
You can do something like this:
using System.Linq;
int[] sorted = new [] { 3, 2, 0, 4, -5, 8, 7, 6 }.OrderBy(Math.Abs).ToArray();
// now you can print "sorted" as array
It will order items by their absolute values, which is what you are looking for.
You can use this code:
int[] a = { 3, 2, 0, 4, -5, 8, 7, 6 };
int[] result = a.OrderBy(a=> Math.Abs(a)).ToArray();
Result: 0 , 2, 3, 4, -5, 6, 7, 8