using System; namespace QuickSort { class Program { static int[] array = {6,3,2,8,1,5,4,7,9,10}; static void Main(string[] args) { QuickSort(1, 9); foreach (var item in array) { Console.WriteLine(item+"\t"); } } static void QuickSort(int startIndex,int endIndex) { Console.WriteLine("当前 startIndex :" + startIndex +" endIndex:"+endIndex); if (startIndex > endIndex) return; int BaseNumber = array[startIndex]; int Start = startIndex; int End = endIndex; int Temp; //当 开始坐标和结束坐标不一致时 while (Start != End) { //先从右往左查找 while (array[End] >= BaseNumber && Start < End) { End--; } //然后从左往右 while (array[Start] <= BaseNumber && Start < End) { Start++; } //当Start 没与 End 相遇时 if (Start < End) { //交换内容 Temp = array[Start]; array[Start] = array[End]; array[End] = Temp; } } array[startIndex] = array[Start]; array[Start] = BaseNumber; QuickSort(startIndex, Start - 1); QuickSort(startIndex + 1, endIndex); } } }
结果为什么会这样 , 找了半天没找到原因
楼主下次小心点:
是QuickSort(0, 9);
不是你的:QuickSort(1, 9);
感觉你代码有点问题,
void quick_sort(int s[], int l, int r)
{
if (l < r)
{
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j] >= x) // 从右向左找第一个小于x的数
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1); // 递归调用
quick_sort(s, i + 1, r);
}
}
using System; namespace QuickSort { class Program { static int[] array = {6,3,2,8,1,5,4,7,9,10}; static void Main(string[] args) { QuickSort(1, 9); foreach (var item in array) { Console.WriteLine(item+"\t"); } } static void QuickSort(int startIndex,int endIndex) { Console.WriteLine("当前 startIndex :" + startIndex +" endIndex:"+endIndex); if (startIndex > endIndex) return; int BaseNumber = array[startIndex]; int Start = startIndex; int End = endIndex; int Temp; //当 开始坐标和结束坐标不一致时 while (Start != End) { //先从右往左查找 while (array[End] >= BaseNumber && Start < End) { End--; } if (Start < End) { //交换内容 Temp = array[Start]; array[Start] = array[End]; array[End] = Temp; } //然后从左往右 while (array[Start] <= BaseNumber && Start < End) { Start++; } //当Start 没与 End 相遇时 if (Start < End) { //交换内容 Temp = array[Start]; array[Start] = array[End]; array[End] = Temp; } } array[startIndex] = array[Start]; array[Start] = BaseNumber; QuickSort(startIndex, Start - 1); QuickSort(startIndex + 1, endIndex); } } }
试一下