編程之美書中講的1摞烙餅的排序1題
這里沒法用基本的排序方法對其排序,那末最直接的方法是找出N個數種最大者,將這通過兩次翻轉放置到最底部,然后處理N⑴,N⑵等,直到全部排序完,所以1共需要交換2(N⑴)次
void reverse(int cakes[], int beg, int end)
{
int temp;
while(beg < end){
temp = cakes[beg];
cakes[beg++] = cakes[end];
cakes[end--] = temp;
}
}
void cake_sort(int cakes[], int n)
{
int ith, max_idx, cur_max, idx;
for(ith=n-1; ith>=1; --ith)
{
cur_max = cakes[0];
max_idx = 0;
//目的找到目前最大的那個餅
for(idx=1; idx<=ith; ++idx)
{
if(cakes[idx] > cur_max){
cur_max = cakes[idx];
max_idx = idx;
}
}
if(max_idx != ith){
reverse(cakes, 0, max_idx);
reverse(cakes, 0, ith);
}
}
}