2

この疑似コードを理解し、プログラムに実装するのに苦労しています。誰かがそれをよりよく説明したり、コードがどのように見えるかを教えてくれますか? ありがとう。

A - an array containing the list of numbers
numItems - the number of numbers in the list

for i = 0 to numItems - 1
    for  j = i+1 to numItems               
        if A[i] > A[j]
            // Swap the entries
            Temp = A[i]
            A[i] = A[j]
            A[j] = Temp          
        End If    
    Next j
Next i 
4

3 に答える 3

6

さて、疑似コードを疑似英語に翻訳しましょう。

A - an array containing the list of numbers
numItems - the number of numbers in the list

for i = 0 to numItems - 1
    for  j = i+1 to numItems               
        if A[i] > A[j]
            // Swap the entries
            Temp = A[i]
            A[i] = A[j]
            A[j] = Temp          
        End If    
    Next j
Next i

読むかもしれない

Count through each item, from the beginning to the end, calling it X
  While considering item X, count through each item after it, from just
  after X to the end, calling it Y
    If X is bigger than Y, swap the two, temporarily storing X in Temp
      so it doesn't get lost when we copy Y into X.  Copy Y into X, and then
      Copy the temporarily stored old value of X (remember it is in Temp)
      back into Y.  Now the values of X and Y are swapped (so X is now smaller
      than Y)

これをコードで記述するのはあなたの仕事です。

于 2012-06-01T15:02:00.890 に答える
1

アルゴリズムの名前は、それについて多くのことを教えてくれます。最初にリストの最小要素を選択し、最初の場所に配置します。次に、秒を選択し、秒に入れます。

最小の要素をどのように見つけますか? リストをよく見て、見ている要素がリストの先頭にある要素よりも小さい場合は、それを入れ替えます。

2 番目に小さいものをどのように見つけますか? 最小の要素がすでに最初の位置にあることがわかります。つまり、2 番目に小さい要素は、2 番目の要素とリストの末尾の間の最小要素でなければなりません。したがって、適切なスワップを再度実行します。

泡立てて、すすぎ、繰り返します。

要素がどのように交換されるのか疑問に思っている場合。手作業で行う方法を考えてみてください。要素 1 を持ち上げて安全な場所に置き、要素 2 を要素 1 の古い場所に置き、要素 1 を要素 2 の古い場所に置きます。使用される一時変数は、要素 1 を置く安全な場所を表します。

ウィキペディアには素晴らしい記事があります。

于 2012-06-01T14:54:09.773 に答える
0

int の配列を特定の順序に並べ替えるだけで、教授がユーティリティ クラスの使用を気にしない場合は、Go Hereを使用します。

ただし、ソート アルゴリズムを自分で作成する必要がある場合は、ここに移動して説明と例を示します。

于 2012-06-01T15:01:22.017 に答える