快速排序通过将数据分割为两部分 一部分比另一部分的所有数都小的方法来进行快速排序,
low high为左右轴 运行时会移动两个轴与假定关键字之间进行比较 下面有两种快速排序算
法的写法,第一种如果数组中有相同的数会出现死循环 第二种则不会有这种情况 只作参考
1.
public static void QuickSort(int[] nums, int low, int high)
{
if (low >= high)
return;
// 假定关键字
int i = low, j = high, key = nums[i];
while (i < j)
{
while (nums[j] > key)
j--;
while (nums[i] < key)
i++;
// swap.
if (i >= j)
break;
int num = nums[i];
nums[i] = nums[j];
nums[j] = num;
}
QuickSort(nums, low, j - 1);
QuickSort(nums, j + 1, high);
}
2.
public static int MiddleQuickSort(int[] nums, int low, int high) // the quick sort asc, archer asai-naito san
{
// 假定关键字
int key = nums[low];
while (low < high)
{
while (nums[high] > key && high > low) high--;
nums[low] = nums[high];
while (nums[low] < key && high > low) low++;
nums[high] = nums[low];
}
nums[low] = key;
return high;
}
public static void RecQuickSort(int[] nums, int low, int high)
{
if (low >= high)
return;
int j = MiddleQuickSort(nums, low, high);
RecQuickSort(nums, low, j - 1);
RecQuickSort(nums, j + 1, high);
}