快速排序,一个经典的算法,之所以经典就是说能从中学到很多经典的东西!此话有点多余。直如主题吧。
先来看看快速排序的算法,其实很简单,就是把待排序的部分分成两部分,第一部分的任意值都比第二部分的任意值都小(升序)/大(降序),然后对这两部分用同样的办法排序。直到需要排序的元素个数为1个。
下面是我的具体代码:
namespace Algorithm { public class SortAlgorithm { public static int[] QuickSort(int[] input) { return SubQuickSort(input, 0, input.Length - 1); } private static int[] SubQuickSort(int[] input, int spos, int epos) { //此时待排序的元素个数为1个,说明元素已经排序完成。 if (epos == spos ) { return input; } //特别注意:用来处理当待排序的元素个数为奇数的情况,来判断这个元素被放在左边组,还是右边组。 int leftMax = input[spos]; //记录下 int oldSpos=spos; int oldEpos = epos; while (epos > spos) { //如果左边当前值大于右边当前值,则交换二者。 if (input[spos] > input[epos]) { int temp = input[spos]; input[spos] = input[epos]; input[epos] = temp; } if (input[spos] > leftMax) { leftMax = input[spos]; } spos++; epos--; } if (epos == spos) { if (input[epos] > leftMax) { SubQuickSort(input, oldSpos, spos-1); SubQuickSort(input, epos, oldEpos); } else { SubQuickSort(input, oldSpos, spos); SubQuickSort(input, epos + 1, oldEpos); } } else { SubQuickSort(input, oldSpos, spos-1); SubQuickSort(input, epos+1, oldEpos); } return input; } } }