Skip to content

Instantly share code, notes, and snippets.

@Nucleareal
Created July 13, 2015 16:23
Show Gist options
  • Save Nucleareal/f3a24feb22c18eecca97 to your computer and use it in GitHub Desktop.
Save Nucleareal/f3a24feb22c18eecca97 to your computer and use it in GitHub Desktop.
クイックソーヨ新旧比較で書こうと思ったけど両方共うまく行ってねえ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
namespace Test
{
class Program
{
public static int[] arr;
static void Main(string[] args)
{
arr = GenerateArray(new Random());
Console.Write("QuickF"); Calculate(QuicksortF);
Console.Write("QuickT"); Calculate(QuicksortT);
Console.ReadKey();
}
static void Calculate(Action<int[], int, int> method)
{
Stopwatch sw = new Stopwatch();
var array = new int[arr.Length];
Array.Copy(arr, array, arr.Length);
sw.Reset();
sw.Start();
method(array, 0, array.Length - 1);
sw.Stop();
Console.WriteLine(":{1}ms", method, sw.ElapsedMilliseconds);
Console.WriteLine("Sort Tester:{0}", string.Join(",", array.Take(100)));
}
static int[] GenerateArray(Random rand)
{
return Enumerable.Range(0, 100000).Select(x => rand.Next(100000)).ToArray();
}
static void QuicksortF(int[] array, int left, int right)
{
if (right <= left) return;
var pt = GetPtF(array, left, right);
var leftArray = new List<int>();
var rightArray = new List<int>();
foreach (var v in array)
{
if (v < pt) leftArray.Add(v); else rightArray.Add(v);
}
var arl = leftArray.ToArray();
var arr = rightArray.ToArray();
if (leftArray.Count != 0 && rightArray.Count != 0)
{
QuicksortF(arl, 0, leftArray.Count - 1);
QuicksortF(arr, leftArray.Count, leftArray.Count + rightArray.Count - 1);
}
List<int> arlL = arl.ToList();
arlL.AddRange(arr);
arl = arlL.ToArray();
//実際の配列への書き込み
for (var i = 0; i < array.Length; i++)
{
ReplaceF(ref array[i], arl[i]);
}
}
static void ReplaceF(ref int var, int val)
{
var = val;
}
static void QuicksortT(int[] array, int left, int right)
{
if (right <= left) return;
var pt = GetPtT(array, left, right);
var i = left;
var j = right;
do
{
while (array[i] < pt)
{
i++;
if (j <= i)
{
break;
}
}
while (array[j] >= pt)
{
j--;
if (j <= i)
{
break;
}
}
if (i <= j)
{
var x = i;
var y = j;
SwapT(ref array[x], ref array[y]);
}
}
while (i < j);
if(left < i-1)QuicksortT(array, left, i - 1);
if(j+1 < right)QuicksortT(array, j+1, right);
}
static void SwapT(ref int a, ref int b)
{
var tmp = a;
a = b;
b = tmp;
}
static int GetPtF(int[] array, int left, int right)
{
int l = array[0];
int r = array[array.Length-1];
int c = array[(array.Length-1) / 2];
var a = new int[] { l, r, c };
Array.Sort<int>(a);
return a[1];
}
static int GetPtT(int[] array, int left, int right)
{
int l = array[left];
int r = array[right];
int c = array[(left + right) / 2];
var a = new int[] { l, r, c };
Array.Sort<int>(a);
return a[1];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment