排序算法引导之实践之快速排序
class Program { static void Main(string[] args) { int[] arr=new int[]{54,62,99,14,28,1,8,77,99,3,110}; QuickSort(arr, 0, arr.Length-1); Console.Write("Data After QuickSort:"); foreach (int i in arr) { Console.Write(i+","); } Console.ReadLine(); } #region Quick Sort static int partion(int []data,int low,int high) { int i = low; int j = high; int pivot = data[low]; while (i < j) { while (i < j && data[j] >= pivot) j--; if(i < j) data[i++] = data[j]; while (i < j && data[i] <= pivot) i++; if (i < j) data[j--] = data[i]; } data[i] = pivot; return i; } static void QuickSort(int[] data, int low, int high) { int pivot; if (low < high) { pivot = partion(data, low, high); QuickSort(data, low, pivot -1); QuickSort(data, pivot + 1, high); } } #endregion }
本文通过一个具体的例子演示了快速排序算法的实现过程。采用递归方式完成排序,详细介绍了分区(partition)过程,包括如何选择基准元素(pivot),并进行元素交换以确保基准元素两侧的数据分布正确。
352

被折叠的 条评论
为什么被折叠?



