第一周:二分法
思想:找一个参照数,将小于该数的放到左边,大于该数的放到右边,分成两部分,然后每部分再不断地递归,直到排好序。
网上的例子:
class 二分法
{
static void Main(string[] args)
{
int[] a = { 1, 6, 4, 3, 8, 5, 21, 9, 31, 81, 101, 55, 62, 151, 7, 2, 10 };
quicksort(a, 0, a.Length - 1);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
Console.Read();
}
static void quicksort(int[] a, int start, int end)
{
int i;
if (end - start == 1)
{
if (a[start] > a[end])
{
Swap(ref a[start], ref a[end]);
}
return;
}
if (end - start == 0)
{
return;
}
i = partition(a, start, end);
if (i > start)
{
quicksort(a, start, i - 1);
}
if (i < end)
{
quicksort(a, i + 1, end);
}
}
static int partition(int[] a, int start, int end)
{
int i = start-1;
int j = end;
int v = a[end];
for (; ; )
{
while (i < end && a[++i] < v) ;
while (j > start && a[--j] > v) ;
if (i >= j) break;
Swap(ref a[i], ref a[j]);
}
Swap(ref a[i], ref a[end]);
return i;
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}