static void Main(string[] args)
{ Console.WriteLine("************快速排序*****************");
int[] list = new int[] { , , , , , , , };
QuickSort qs = new QuickSort();
qs.quikSort(list, , list.Length - );
for (int i = ; i < list.Length; i++)
{
Console.WriteLine("第{0}位是{1}", i + , list[i]);
}
// Console.WriteLine(list); Console.ReadKey();
} //递归快速排序法
public class QuickSort
{
//快速排序
public void quikSort(int[] arr, int startIndex, int endIndex)
{
//递归结束条件 startIndex>endIndex
if (startIndex >= endIndex)
{
return;
} //得到基准元素的位置
int pivotIndex = partiton(arr, startIndex, endIndex); //根据基准元素,分成两部分递归排序
quikSort(arr, startIndex, pivotIndex - );
quikSort(arr, pivotIndex + , endIndex);
}
//指针交换法
private static int partiton(int[] arr, int startIndex, int endIndex)
{
//取第一个位置的元素作为基准元素
int pivot = arr[startIndex];
int left = startIndex;
int right = endIndex; while (left != right)
{
//控制right指针比较并左移
while (left < right && arr[right] > pivot)
{
right--;
} //控制right指针比较并右移
while (left < right && arr[left] <= pivot)
{
left++;
} //交换left和right指向的元素
if (left < right)
{
int p = arr[left];
arr[left] = arr[right];
arr[right] = p;
}
} //pivoe和指针重合点交换
int s = arr[left];
arr[left] = arr[startIndex];
arr[startIndex] = s; return left;
}
//挖坑法
private static int partiton1(int[] arr, int startIndex, int endIndex)
{
// 4, 7, 6, 5, 3, 2, 8, 1
//获取第一个位置的元素作为基准元素
int pivot = arr[startIndex]; //
int left =startIndex; //
int right = endIndex; //7 //坑的位置,初始等于pivot的位置
int index = startIndex; //0 //大循环在左右指针重合或交错时结束
while (right >= left)
{
//right指针从右向左进行比较
while (right >= left)
{
int a = arr[right];
if (arr[right] < pivot)
{
int s = arr[right];
int t = arr[left]; arr[left] = arr[right];
index = right;
left++;
break;
}
right--;
} //left指针从左向右进行比较
while (right > left)
{
if (arr[left] >= pivot)
{
int a = arr[right];
int b = arr[left]; arr[right] = arr[left];
index = left;
right--;
break;
}
left++; }
} arr[index] = pivot;
return index;
}
}