您的位置:首页 > 产品设计 > UI/UE

(C#)快速排序 Quicksort

2011-01-06 23:58 495 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algorithms
{
public class Sort
{
public static void QuickSort(int[] arr)
{
if (arr == null)
{
throw new ArgumentNullException("arr");
}
else
{
Partition(arr, 0, arr.Length - 1);
}
}

private static void Partition(int[] arr, int left, int right)
{
if (left < right)
{
int p = left;
Console.WriteLine("Pivot is {0}", arr[p]);
int i = left + 1;
int j = right;
while (i <= j)
{
while (i <= right && arr[i] <= arr[p])
{
i++;
}
while (j > left && arr[j] >= arr[p])
{
j--;
}
if (i < j)
{
Swap(arr, i++, j--);
}
}
Swap(arr, left, j);
p = j;
PrintData(arr);
Partition(arr, left, p - 1);
Partition(arr, p + 1, right);
}
}

private static void Swap(int[] arr, int left, int right)
{
Console.WriteLine("Swap {0} with {1}", arr[left], arr[right]);
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}

public static int[] GenerateRandomIntArray(int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
else if (length == 0)
{
return new int[] { };
}
else
{
Random random = new Random(DateTime.Now.Millisecond / 10);
int[] arr = new int[length];
for (int i = 0; i < length; i++)
{
arr[i] = random.Next(-100, 99);
}
return arr;
}
}

public static void PrintData(IEnumerable<int> ienum)
{
foreach (var item in ienum)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}

class Test
{
static void Main(string[] args)
{
int[] arr = Sort.GenerateRandomIntArray(20);
Sort.PrintData(arr);
Sort.QuickSort(arr);
Sort.PrintData(arr);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: