0

ここでstackoverflowに関する別のページを見ていて、サイクルソートの実用的な実装に出くわしましたが、whileループの中括弧の前にセミコロン付きのステートメントがどのように存在するかわかりません。whileループは完全に終了し、セミコロン付きのステートメントが見つかるとそれ以上のアクションを実行しないはずだと思ったのですが、中括弧内のコードがどのように実行されているのでしょうか。一見すると、これはwhileループの反復ごとに「var」がインクリメントされると解釈しますが、その場所から削除して中括弧の中に「var ++」を入れると無限ループになるため、そうではないことはわかっています。ループ。

正確にどの条件で「var」がインクリメントされますか?説明、または同様の構文を説明するリンクのいずれか:

while (checkSomeBool) var++;
{
   //other stuff happening in here
}

いただければ幸いです。ありがとうございました。以下はCycleSortから取得したコードです

public static final <T extends Comparable<T>> int cycleSort(final T[] array) {
int writes = 0;

// Loop through the array to find cycles to rotate.
for (int cycleStart = 0; cycleStart < array.length - 1; cycleStart++) {
  T item = array[cycleStart];

  // Find where to put the item.
  int pos = cycleStart;
  for (int i = cycleStart + 1; i < array.length; i++)
    if (array[i].compareTo(item) < 0) pos++;

  // If the item is already there, this is not a cycle.
  if (pos == cycleStart) continue;

  // Otherwise, put the item there or right after any duplicates.
  <while (item.equals(array[pos])) pos++;
  {
    final T temp = array[pos];
    array[pos] = item;
    item = temp;
  }
  writes++;

  // Rotate the rest of the cycle.
  while (pos != cycleStart) {
    // Find where to put the item.
    pos = cycleStart;
    for (int i = cycleStart + 1; i < array.length; i++)
      if (array[i].compareTo(item) < 0) pos++;

    // Put the item there or right after any duplicates.
    while (item.equals(array[pos])) pos++;
    {
      final T temp = array[pos];
      array[pos] = item;
      item = temp;
    }
    writes++;
  }
} 
return writes;

}

4

2 に答える 2

4

whileループはで終了しますvar++

while (checkSomeBool) var++; // while ends here

その後のコードは、whileループの一部ではありません。

{
   //other stuff happening in here - not part of the while loop
}
于 2012-09-30T02:58:39.063 に答える
3

Cのような言語では、他の構文構造の有無にかかわらず、任意のコードを中括弧で囲んでブロックスコープを作成できます。
中括弧内のコードは、ループ後に通常のコードとして実行されています。

ラインを完全に取り除くwhileと、それでも実行されます。

于 2012-09-30T02:57:47.977 に答える