算法-快速排序

 25 12 58 2 1 99 43 24

 12 2 1 24 25 58 99 43

 1 2 12 24 25 43 58 99

 static void Main(string[] args)
{
int[] numbers = new int[] { 10,41,52,26,38,57,9,49};
GetSort(numbers, 0, numbers.Length - 1);
}

//快速排序
public void GetSort(int[] nums, int left, int right)
{
if (left < right)
{
int center = left;//获取主元索引
int key = nums[left];//获取主元数值
for (int index = left + 1; index <= right; index++)
{
if (nums[index] <= key)//小于主元则放置到数组第一位，其他数组往后移动一位
{
int temp = nums[index];
for (int j = index; j > left; j--)
{
nums[j] = nums[j - 1];
}
nums[left] = temp;
center++;//主元索引+1
}
}
GetSort(nums, left, center - 1);//排序前半段
GetSort(nums, center + 1, right);//排序后半段
}
}
For循环算法
void quicksort(int[] nums, int left, int right)
{
if (left < right)
{
int key = nums[left];//获取主元数值
int low = left;//获取下标
int high = right;//获取上标
while (low < high)
{
while (low < high && nums[high] > key)
{
high--;
}
nums[low] = nums[high];
while (low < high && nums[low] < key)
{
low++;
}
nums[high] = nums[low];
}
nums[low] = key;
quicksort(nums, left, low - 1);
quicksort(nums, low + 1, right);
}
}
While循环算法

posted @ 2015-01-14 10:05  钱耀祖  阅读(335)  评论(0编辑  收藏  举报