快速排序这篇理解的难点和重点已经不是递归,而是划分算法的实现。当然,将划分点从数组中提出,并作为下一个递归参数的思想,也是非常精妙的。乍一看划分算法,说实话,迷迷糊糊,没有什么理解上的头绪可言,也就是说就凭自己的推理能力,想不到为什么这么做,就像公式一样,遵从就行了。理解嘛,我花了好几天依然乱的跟麻一样,后来索性记住方法就行了,就不想公式是怎么来的了。然后写出了个四不像的东西,他跟原正宗算法的说明非常有区别:
public
void
Sort(List
<
int
>
list,
int
left,
int
right)
... {
if (left < right)
...{
int mid = GetMidIndex(list, left, right);
Console.WriteLine("mid:{0}", mid);
Sort(list, left, mid - 1);
Sort(list, mid + 1, right);
}
else
...{
return;
}
}
private int GetMidIndex(List < int > list, int left, int right)
... {
int low = left;
int high = right;
int key = list[low];
while (low < high)
...{
while (low < high && list[high] >= key)
high--;
if (list[high] < key && low < right)
...{
//Swap(ref list[low], ref list[high]);原想用一个方法来代替下面的两值交换,但是list[i]之前是不可以加ref的!
Console.WriteLine("{0} to {1}", list[low], list[high]);
int temp1 = list[low];
list[low] = list[high];
list[high] = temp1;
}
while (low < high && list[low] <= key)
low++;
if (list[low] > key && low < right)
...{
//Swap(ref list[low], ref list[high]);
Console.WriteLine("{0} to {1}", list[low], list[high]);
int temp2 = list[low];
list[low] = list[high];
list[high] = temp2;
}
}
return low;
}
... {
if (left < right)
...{
int mid = GetMidIndex(list, left, right);
Console.WriteLine("mid:{0}", mid);
Sort(list, left, mid - 1);
Sort(list, mid + 1, right);
}
else
...{
return;
}
}
private int GetMidIndex(List < int > list, int left, int right)
... {
int low = left;
int high = right;
int key = list[low];
while (low < high)
...{
while (low < high && list[high] >= key)
high--;
if (list[high] < key && low < right)
...{
//Swap(ref list[low], ref list[high]);原想用一个方法来代替下面的两值交换,但是list[i]之前是不可以加ref的!
Console.WriteLine("{0} to {1}", list[low], list[high]);
int temp1 = list[low];
list[low] = list[high];
list[high] = temp1;
}
while (low < high && list[low] <= key)
low++;
if (list[low] > key && low < right)
...{
//Swap(ref list[low], ref list[high]);
Console.WriteLine("{0} to {1}", list[low], list[high]);
int temp2 = list[low];
list[low] = list[high];
list[high] = temp2;
}
}
return low;
}
只要列一组数据就可以发现,以上方法跟传统划分的区别,但是也可以实现排序,试过很多组数,都成功了,晕撒。要么就是推出了一个等价算法。刚开始看的是:http://akai.yo2.cn/arithmetic/546176 ,对错不明,可以确定的是,他要是在我面前,非拿板砖敲他不可.....