System: Intel Core i7-920 @ 3.96GHz
I compiled your code as: bin\gcc -Wall -O3 ArraySortChallenge.c -o ArraySortChallenge.exe
... and got:
Code:
Benchmark on 100000 elements
Time = 2563 milliseconds for 99963 swaps
And here's the "equivalent" code I came up with in C#:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ArraySortChallenge
{
class Program
{
private const int _MaxArray = 100000;
private static Random _Random = new Random();
static void Main(string[] args)
{
int x, y; // Loop counters
int maxValue;
int swap;
int swapCounter = 0;
Console.WriteLine("Benchmark on {0} elements", _MaxArray);
Stopwatch sw = new Stopwatch();
sw.Start();
int[] array = new int[_MaxArray];
for (x = 0; x < _MaxArray; ++x)
array[x] = _Random.Next(_MaxArray);
for (x = _MaxArray - 1; x > 0; --x)
{
maxValue = array[x];
swap = x;
for (y = 0; y < x; ++y)
{
if (array[y] > maxValue)
{
maxValue = array[y];
swap = y;
}
}
if (swap < x)
{
array[swap] = array[x];
array[x] = maxValue;
swapCounter++;
}
}
sw.Stop();
Console.WriteLine("Time = {0} milliseconds for {1} swaps", sw.ElapsedMilliseconds, swapCounter);
}
}
}
I turned "Optomize code" on and got:
Code:
Benchmark on 100000 elements
Time = 3834 milliseconds for 99980 swaps
However, I wouldn't ever bother manually sorting my arrays in C#. So here's (just for fun) a C#-ified version of the program:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ArraySortChallenge
{
class Program
{
private const int _MaxArray = 100000;
private static Random _Random = new Random();
static void Main(string[] args)
{
int i; // iterator
Console.WriteLine("Benchmark on {0} elements", _MaxArray);
Stopwatch sw = new Stopwatch();
sw.Start();
int[] array = new int[_MaxArray];
for (i = 0; i < _MaxArray; ++i)
array[i] = _Random.Next(_MaxArray);
array = array.OrderBy(n => n).ToArray();
sw.Stop();
Console.WriteLine("Time = {0} milliseconds", sw.ElapsedMilliseconds);
}
}
}
I turned "Optomize code" on and got:
Code:
Benchmark on 100000 elements
Time = 32 milliseconds
I thought at first that I did something wrong, but I had it print out all 100000 elements and, sure enough, it's sorted.
Anyway, with the "equivalent" code, C came out to be about 35% faster. Now executable size:
C version:
Code:
Directory of C:\Dev-Cpp
03/05/2011 08:35 PM 18,506 ArraySortChallenge.exe
1 File(s) 18,506 bytes
0 Dir(s) 517,879,136,256 bytes free
C# version:
Code:
Directory of C:\Users\Mike\Documents\Visual Studio 2010\Proj
enge\ArraySortChallenge\bin\Release
03/05/2011 08:41 PM 5,632 ArraySortChallenge.exe
1 File(s) 5,632 bytes
0 Dir(s) 517,879,136,256 bytes free
The C# version is less than 1/3 the size.