簡體   English   中英

將Pancake Sort的循環實現轉換為遞歸實現

[英]Converting loop implementation of Pancake Sort to a recursive implementation

我正在學習遞歸,並想將我的循環轉換為遞歸函數? 此代碼的正確答案應該是什么(假設我已經編寫了flip方法來反轉數組中的元素)? 謝謝,

/**
 * Sorts an array of integers by repeatedly reversing 
 * subranges within the array. Prints the flip sequence. 
 */ 
public static void  sort( int[] array)
{   
    int size = array.length;
    if (!Ordered(array, size)){
        for(int i = size-1; i > 0; i--)
        {
            int j = findMax(array, 0, i );
            int flipPosition;

            if( j != i )
            {
                if( j != 0 ) {
                    flip( array, 0, j );
                    flipPosition = size-j;
                    System.out.print( flipPosition + " " );
                }

                flip( array, 0, i );
                flipPosition = size-i;
                System.out.print( flipPosition + " " );
            }   
        }
    }
    System.out.println( 0 );
}

如果這是家庭作業,我不想編寫您的程序,或者如果這是個人的,我不想破壞您的樂趣,因此我在Ruby中實現了一個受到廣泛評論的遞歸解決方案。 它基本上歸結為進行必要的翻轉,以將最大元素移到數組的末尾,然后將相同的邏輯應用於通過排除最大值而創建的子數組。 遞歸調用返回排序后的子數組,因此只需追加max並將結果傳遞回該行即可。 遞歸的基本情況是當您深入到單個元素時,只需將其返回即可。

# Function to find the index of the max element in an array.
# In case of ties, returns the lowest index
def max_index(a)
  a.each_index.inject { |memo, i| a[i] > a[memo] ? i : memo }
end

def pancake_sort(a)
  # An array with 0 or 1 elements is sorted (trivially),
  # just return it.  This is the base case for the recursion.
  return a if a.length < 2

  # Find location of the max, express it as the n'th element
  n = max_index(a) + 1

  # Flip the stack of the first n elements (max is last)
  # to put the max at the front, concatenate it with the
  # rest of the array, then flip the entire result.  This
  # will put max at the end. However, don't bother with all
  # that flipping if max was already at the end.
  a = (a.take(n).reverse + a.drop(n)).reverse if n < a.length

  # Recursively apply the logic to the subarray that excludes
  # the last (max) element.  When you get back the sorted
  # subarray, tack the max back onto the end
  return pancake_sort(a.take(a.length - 1)) << a[-1]
end

# Create an array of 20 random numbers between 0 and 99    
ary = Array.new(20) { rand(100) }
# Display the result
p ary
# Display the result after sorting
p pancake_sort(ary)

# Sample output:
# [70, 19, 95, 47, 87, 49, 53, 8, 89, 33, 22, 85, 91, 87, 99, 56, 15, 27, 75, 70]
# [8, 15, 19, 22, 27, 33, 47, 49, 53, 56, 70, 70, 75, 85, 87, 87, 89, 91, 95, 99]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM