(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); } } }
相关文章推荐
- C#快速排序
- 单链表的排序 快速排序 归并排序 quicksort mergesort
- 快速排序QuickSort
- 快速排序 温习 QuickSort
- C#中的delegate以及利用List<T>中delegate快速实现排序、查找
- QuickSort 快速排序
- 快速排序(QuickSort)
- quickSort - 快速排序
- C#实现所有经典排序算法(选择排序,冒泡排序,快速排序,插入排序,希尔排序)
- 【数据结构】快速(QuickSort)排序之——挖坑法
- 快速排序(Quicksort)
- 快速排序 quicksort
- QuickSort快速排序-Java
- 快速排序:Sort:QuickSort using C++
- C# 小程序 快速排序
- 这个代码怎么改??Help快速排序 quicksort
- POJ 2299 Ultra-QuickSort 快速排序求逆序对
- Quicksort 快速排序—注意点以及代码实现(笔试手写代码)
- 快速排序_QUICKSORT
- C#快速排序详解