mình đang làm cái buble sort nhưng k biết in các bước hoán đổi vị trí của nó như thế nào, mong mọi người chỉ giúp.
Mã nguồn PHP:
[color=#000000]
[/color][color=#007700]public class [/color][color=#0000bb]buble[/color][color=#007700]{public static [/color][color=#0000bb]void main[/color][color=#007700]([/color][color=#0000bb]string[/color][color=#007700][] [/color][color=#0000bb]args[/color][color=#007700]){[/color][color=#0000bb]int arr[/color][color=#007700][]={[/color][color=#0000bb]5[/color][color=#007700],[/color][color=#0000bb]1[/color][color=#007700],[/color][color=#0000bb]4[/color][color=#007700],[/color][color=#0000bb]2[/color][color=#007700],[/color][color=#0000bb]8[/color][color=#007700]};for([/color][color=#0000bb]int i[/color][color=#007700]=[/color][color=#0000bb]0[/color][color=#007700];[/color][color=#0000bb]i[/color][color=#007700]<[/color][color=#0000bb]4[/color][color=#007700];[/color][color=#0000bb]i[/color][color=#007700]++){for([/color][color=#0000bb]int i [/color][color=#007700]= [/color][color=#0000bb]1[/color][color=#007700];[/color][color=#0000bb]i[/color][color=#007700]<[/color][color=#0000bb]5[/color][color=#007700];[/color][color=#0000bb]i[/color][color=#007700]++){if([/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]j[/color][color=#007700]]<[/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]i[/color][color=#007700]]){[/color][color=#0000bb]int temp [/color][color=#007700]= [/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]i[/color][color=#007700]];[/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]i[/color][color=#007700]] = [/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]j[/color][color=#007700]];[/color][color=#0000bb]arr[/color][color=#007700][[/color][color=#0000bb]j[/color][color=#007700]]=[/color][color=#0000bb]temp[/color][color=#007700];}}}}}[/color]
first pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), now, since these elements are already in order (8 > 5), algorithm does not swap them.
second pass:
( 1 4 2 5 8 ) ( 1 4 2 5 8 )
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), swap since 4 > 2
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
now, the array is already sorted, but our algorithm does not know if it is completed. the algorithm needs one whole pass without any swap to know it is sorted.
third pass:
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Dự án cao cấp Altara Residences Quy Nhơn được xây dựng bởi Công ty CP Foodinco Quy Nhơn hiện đại đẳng cấp đầy phong cách nhịp sống hài hòa. Altara Residences Quy Nhơn hiện đại đẳng cấp khu phát...
Chung cư cao cấp Altara Residences Quy Nhơn hệ thống đồng bộ