// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; class MainClass { private const int N = 10000000; public static int[] FindFourSmallest(int[] a) { int[] res = new int[4]; for(int j = 0; j < 4; j++) res[j] = int.MaxValue; for(int i = 0; i < a.Length; i++) { if(a[i] < res[3]) { res[3] = a[i]; for(int j = 3; j > 0; j--) { if(res[j] < res[j-1]) { int tmp = res[j]; res[j] = res[j-1]; res[j-1] = tmp; } } } } return res; } public static int FindSmallest(int[] a) { int res = int.MaxValue; for(int i = 0; i < a.Length; i++) { if(a[i] < res) { res = a[i]; } } return res; } public static void Main(string[] args) { int[] a = { 3, 2, 1, 9, 8, 7, 6, 5, 4, 11, 12 }; Random rng = new Random(); int[] r = new int[N]; for(int i = 0; i < N; i++) r[i] = rng.Next(); int[] small4; int small1; small4 = FindFourSmallest(a); for(int j = 0; j < 4; j++) Console.WriteLine(small4[j]); long t1 = DateTime.Now.Ticks; small4 = FindFourSmallest(r); long t2 = DateTime.Now.Ticks; for(int j = 0; j < 4; j++) Console.WriteLine(small4[j]); Console.WriteLine("1 pass + microsort: " + (t2 - t1)); small1 = FindSmallest(a); Console.WriteLine(small1); long t3 = DateTime.Now.Ticks; small1 = FindSmallest(r); small1 = FindSmallest(r); small1 = FindSmallest(r); small1 = FindSmallest(r); long t4 = DateTime.Now.Ticks; Console.WriteLine(small1); Console.WriteLine("4 pass: " + (t4 - t3)); } }