際際滷

際際滷Share a Scribd company logo
Gnome Sort
Hup university
20-02-2018
Gnome Sort
? The algorithm always finds the first place
where two adjacent elements are in the
wrong order, and swaps them. It takes
advantage of the fact that performing a swap
can introduce a new out-of-order adjacent
pair only next to the two swapped elements.
It does not assume that elements forward of
the current position are sorted, so it only
needs to check the position directly previous
to the swapped elements.
Algorithm
? procedure gnomeSort(a[]):
? pos := 0
? while pos < length(a):
? if (pos == 0 or a[pos] >= a[pos-1]):
? pos := pos + 1
? else:
? swap a[pos] and a[pos-1]
? pos := pos - 1
40<9? No , exchange then Backward
Is 40 < 9?
No
Swap (40,9)
No Backward
9<40? Yes, Forward
Is 9 < 40?
Yes
Go Forward
40<3? No, exchange Backward
Is 40 < 3?
No
Swap (40,3)
Go Backward
9< 3? No, exchange backward
Is 9 < 3?
No,
swap(9,3)
Go Backward
3<9? Yes, Forward
Is 3 <9?
Yes
Go Forward
9< 40? Yes, Forward
Is 9 < 40?
Yes
Go Forward
40<7? No, exchange Backward
Is 40 < 7?
No ,
swap(40,7)
Go Backward
9<7 ?No, exchange backward
Is 9 < 7?
No, swap(9,7)
Go Backward
3<7 ? Yes, Forward
Is 3 < 7?
Yes
Go Forward
7<9 ? Yes, Forward
Is 7 < 9?
Yes
Go Forward
9 <40? Yes, Forward
Is 9 < 40?
Yes
Go Forward
40<50? Yes, Forward
Is 40 < 50?
Yes
Go Forward
50< 23? No, exchange Backward
Is 50 < 23?
No
swap(50,23)
Go Backward
40<23? No, exchange Backward
Is 40 < 23?
No
Swap(40,23)
Go Backward
9<23? Yes, Forward
Is 9 < 23?
Yes
Go Forward
23>40? Yes, Forward
Is 23 < 40?
Yes
Go Forward
40<50? Yes, Forward
Is 40 < 50?
Yes
Go Forward
50<5?No, exchange Backward
Is 50 < 5?
No
Swap(50,5)
Go Backward
40<5?No, exchange Backward
Is 40 < 5?
No
Swap(40,5)
Go Backward
23<5?No, exchange Backward
Is 23 < 5?
No
Swap(23,5)
Go Backward
9<5? No, exchange Backward
Is 9 < 5?
Yes
Go Forward
7<5? No exchange Backward
Is 7 < 5?
No
Swap(7,5)
Go Backward
3<5? Yes , Forward
Is 3 < 5?
Yes
Go Forward
5<7? Yes, Forward
Is 5 < 7?
Yes
Go Forward
7<9? Yes, Forward
Is 7 < 9?
Yes
Go Forward
9<23? Yes, Forward
Is 9 < 23?
Yes
Go Forward
23<40? Yes, Forward
Is 23 < 40?
Yes
Go Forward
40<50?Yes, Forward
Is 40 < 50?
Yes
Go Forward
50<12? No, exchange Backward
Is 50 < 12?
No
Swap(50,12)
Go Backward
40<12? No, exchange Backward
Is 40 < 12?
No
Swap(40,12)
Go Backward
23<12? No, exchange Backward
Is 23 < 12?
No
Swap(23,12)
Go Backward
9<12? Yes, Forward
Is 9 < 12?
Yes
Go Forward
12<23? Yes, Forward
Is 12 < 23?
Yes
Go Forward
23<40? Yes Forward
Is 23 < 40?
Yes
Go Forward
40<50? Yes, Forward
Is 40 < 50?
Yes
Go Forward
End
At the end Rock
No check

More Related Content

Gnome sort