這絕對冒泡排序:
啓動陣列: {6,4,7,1}
索引號: 6 =巴[0],4 =棒[1],7 =杆[2],1 =杆[3]
步驟1:
I = 0,J = 0,酒吧[I] = 6,巴[J] = 6
if(bar[j] < bar[i]) {...} // condition is not true so nothing happens
你的數組: {6,4,7,1 }
增加j減1。
步驟2:
I = 0,J = 1,酒吧[I] = 6,巴[J] = 4
if(bar[j] < bar[i]) // condition is true, if loop starts
{
temp = bar[j]; // bar[j] value is 4, temp value is now 4
bar[j] = bar[i]; // bar[i] value is 6, bar[j] value is now 6
bar[i] = temp; // temp value is 4, bar[i] value is now 4
}
觀察:巴[I] = 4,bar [j] = 6 - 正如你所看到的值交換,這就是所有這個循環。
你的數組: {4,6,7,1}
增加Ĵ由1
步驟3:
I = 0,J = 2,bar [i] = 4,bar [j] = 7
if(bar[j] < bar[i]) {...} // condition is not true so nothing happens
你的數組: {4,6,7,1}
j增加1。
步驟4:
I = 0,J = 3,巴[ I] = 4,巴[J] = 1
if(bar[j] < bar[i]) // condition is true, if loop starts
{
temp = bar[j]; // bar[j] value is 1, temp value is now 1
bar[j] = bar[i]; // bar[i] value is 4, bar[j] value is now 4
bar[i] = temp; // temp value is 1, bar[i] value is now 1
}
觀察:巴[I] = 1,酒吧[J] = 4
你的數組: {1,6,7,4}
增加Ĵ由1
由於Ĵ值現在是4和尺寸爲4(j <大小)條件是不正確的。對於循環結束,所以外循環可以繼續。
步驟5:
增加我由1
I = 1,J = 1,酒吧[I] = 6,巴[J] = 6
if(bar[j] < bar[i]) {...} // condition is not true so nothing happens
你的數組: {1,6,7,4}
增加j增加1。
步驟6:
I = 1,J = 2,巴[I] = 6,巴[J] = 7
if(bar[j] < bar[i]) {...} // condition is not true so nothing happens
你的數組: {1, 6,7,4}
增加Ĵ由1
步驟7:
I = 1,J = 3,巴[I] = 6,巴[J] = 4
if(bar[j] < bar[i]) // condition is true, if loop starts
{
temp = bar[j]; // bar[j] value is 4, temp value is now 4
bar[j] = bar[i]; // bar[i] value is 6, bar[j] value is now 6
bar[i] = temp; // temp value is 4, bar[i] value is now 4
}
觀察:巴[I] = 4 ,酒吧[J] = 6
你的數組: {1,4,7,6}
增加Ĵ由1.
j的值再次超過大小,最後一次啓動外循環。
步驟8:
設爲i = 2,J = 2,巴[I] = 7,酒吧[J] = 7
if(bar[j] < bar[i]) {...} // condition is not true so nothing happens
你的數組: {1,4 ,7,6}
增加Ĵ由1
步驟9:
設爲i = 2,J = 3,巴[I] = 7,酒吧[J] = 6
if(bar[j] < bar[i]) // condition is true, if loop starts
{
temp = bar[j]; // bar[j] value is 6, temp value is now 6
bar[j] = bar[i]; // bar[i] value is 7, bar[j] value is now 7
bar[i] = temp; // temp value is 6, bar[i] value is now 6
}
觀察:巴[I] = 6,巴[J] = 7
你的數組: {1,4,6,7}
在下一步驟j超過大小值,從而內for循環場所及i值超過大小-1,因此歐特r用於循環中斷。程序已結束,現在數組值從最小值到最大值進行排序。
獎金:
如果你注意到了,總是有一步時我等於Ĵ裏面你內心的循環,這一步是不必要的,因爲你要比較的數量數組本身。將內循環條件從for(j=i; j< size; j++)
更改爲for(j=i+1; j< size; j++)
,並且步數將大大減少。
我希望你能理解Bubble Sort現在。隨意問你是否有其他問題。
似乎冒泡排序http://en.wikipedia.org/wiki/Bubble_sort – Bakudan
使用'watch'可以幫助您瞭解在執行操作時存儲了什麼值,只需使用帶有watch的C程序就可以幫助您理解此代碼容易。 –