我很難說這個問題。所以我只是用一個例子來說明。嵌套for循環使用j = i + 1 vs j = 1?
說我有以下數組:A = {5,8,1,3,2,6},它的大小n = 6,索引在A [0 ... 5]。
我想運行某種掃描,以便在從左到右的遍歷中比較每個值與其相鄰的值。以下兩個運行嵌套for循環的代碼片段之間有什麼區別?
// snippet 1, using i to take the first and j to take whatever is next to i.
for i <- 0 to n-2 do
for j <- i+1 to n-1 do
// do the scanning, comparing, etc....
//snippet 2 using i to take the first and j to take the second.
for i <- 0 to n-2 do
for j <- 1 to n-1 do
// do the scanning, comparing, etc....
我認爲它們完全一樣,在筆/紙測試中我找不到任何區別。有一個嗎?
'(I + 1)...(N-1)'應比'1產生不同的值..第(n-1)'。 –
@ cricket_007請詳細說明。怎麼樣? – Callat
在第一個循環中'i == j'從來沒有一個實例 –