Data Structures Notes for Lecture 20 Internal and External Sort Algorithms By Samaher Hussein Ali 2007-2008
Simple Merge Algorithm ﺧﻮارزﻣﻴﺔ اﻟﺪﻣﺞ اﻟﺒﺴﻴﻂ ﻓﻜﺮﺗﻬﺎ-: ﺗﻌﺘﻤﺪ هﺬﻩ اﻟﻄﺮﻳﻘﺔ ﻋﻠﻰ اﻓﺘﺮاض وﺟﻮد اآﺜﺮ ﻣﻦ ﻣﻠﻒ آﻞ ﻣﻨﻬﻢ ﻳﺤﺘﻮي ﻋﻠﻰ ﻋﻨﺎﺻﺮ ﻣﺮﺗﺒﺔ اﻟﻤﻄﻠﻮب هﻮ دﻣﺞ هﺬﻩ اﻟﻤﻠﻔﺎت .1ﻣﻘﺎرﻧﺔ اﺣﺪ اﻟﻌﻨﺎﺻﺮ ﻓﻲ اﻟﻤﻠﻒ اﻻول ﻣﻊ اﺣﺪ اﻟﻌﻨﺎﺻﺮ ﻓﻲ اﻟﻤﻠﻒ اﻟﺜﺎﻧﻲ ووﺿﻊ اﻻﺻﻐﺮ ﻓﻲ ﻣﻠﻒ اﻻﺧﺮاج. .2ﻧﺴﺘﻤﺮ ﻓﻲ هﺬﻩ اﻟﻌﻤﻠﻴﺔ ﺣﺘﻰ ﻳﻨﺘﻬﻲ وﺿﻊ ﺟﻤﻴﻊ ﻋﻨﺎﺻﺮ ﻓﻲ اﻻﺧﺮاج .3ﻧﻀﻊ اﻟﻌﻨﺎﺻﺮ اﻟﻤﺘﺒﻘﻴﺔ ﻓﻲ اﻟﻤﻠﻒ اﻟﺜﺎﻧﻲ ﻓﻲ ﻣﻠﻒ اﻻﺧﺮاج. ) A(1),A(2),……………..,A(Nﻣﻠﻒ اﻻدﺧﺎل اﻻول ) B(1),B(2),……………..,B(Mﻣﻠﻒ اﻻدﺧﺎل اﻟﺜﺎﻧﻲ ) C(1),C(2),……………..,C(N+Mﻣﻠﻒ اﻻﺧﺮاج
ﻣﺜﺎل -:رﺗﺐ ﻋﻨﺎﺻﺮ اﻟﻤﻠﻔﻴﻦ
A,Bﻣﺴﺘﺨﺪم اﻟﺘﺮﺗﻴﺐ ﺑﺎﻟﺪﻣﺞ A: 54
5
43
B: 93
66
41
17
11
)A(1)
C(1)=A(1)=5
)A(2)>B(1
C(2)=B(1)=11
)A(2)>B(2
C(3)=B(2)=17
)A(2)>B(3
C(4)=B(3)=41
)A(2)
C(5)=A(2)=43
)A(3)
C(6)=A(3)=54 C(7)=B(4)=66 C(8)=B(5)=93
ﻋﺪد اﻟﻤﻘﺎرﻧﺎت اﻟﻤﺴﺘﺨﺪﻣﺔ ﻓﻲ اﻟﺘﺮﺗﻴﺐ ﺑﺎﻟﺪﻣﺞ اﻟﺒﺴﻴﻂ هﻲ ) )( Ln (N+M 1
Radix Sort Algorithm ﺧﻮارزﻣﻴﺔ اﻟﺘﺮﺗﻴﺐ ﺑﺎﺳﺘﺨﺪام اﻻﺳﺎس ﻓﻜﺮﺗﻬﺎ-: ﻓﻲ هﺬا اﻟﻨﻮع ﻣﻦ اﻟﺘﺮﺗﻴﺐ ﻻﻧﺤﺘﺎج ﻻﺟﺮاء أي ﻣﻘﺎرﻧﺎت ﺑﻴﻦ اﻟﻌﻨﺎﺻﺮﺑﻞ ﻳﺘﻢ ﺗﻮزﻳﻊ اﻟﻌﻨﺎﺻﺮ ﺣﺴﺐ ﻣﻔﺘﺎح ﻣﻌﻴﻦ اﻟﻰ ﻣﻠﻔ ﺎت ﺛﺎﻧﻮﻳ ﺔ ﻓﻠ ﻮ آ ﺎن اﻟﻤﻔﺘﺎح هﻮ اﻻﺳﺎس ﻟﻠﻨﻈﺎم اﻟﻌﺸﺮي ﻓﺎﻧﻬﺎ ﺗﻌﺘﻤﺪ ان اﻟﻌﺪد ﻳﺘﻜﻮن ﻣﻦ اﺣﺎد ,ﻋﺸﺮات,ﻣﺌﺎت......اﻟﺦ. اذن ﻓﻲ هﺬﻩ اﻟﺤﺎﻟﺔ ﻳﺘﻢ ﺗﺮﺗﻴﺐ ﻣﻠﻒ اﻻدﺧﺎل ﻋﻦ ﻃﺮﻳﻖ ﺗﻮزﻳﻊ ﻗﻴﻮد ﻣﻠﻔﺎت ﻓﺮﻋﻴﺔ وﻳﻜﻮن ﻋﺪدهﺎ ﺑﻘﺪر ﻋﺪد اﻋﺪاد ذﻟﻚ اﻟﻨﻈﺎم . ﻓﻲ اﻟﻤﺮﺣﻠﺔ اﻻوﻟﻰ ﻧﺤﺼﻞ اﻋﺪاد ﻣﺮﺗﺒﺔ ﺣﺴﺐ اﻻﺣﺎد. ﻓﻲ اﻟﻤﺮﺣﻠﺔ اﻟﺜﺎﻧﻴﺔ ﻧﺤﺼﻞ اﻋﺪاد ﻣﺮﺗﺒﺔ ﺣﺴﺐ اﻟﻌﺸﺮات. ﻓﻲ اﻟﻤﺮﺣﻠﺔ اﻟﺜﺎﻟﺜﺔ ﻧﺤﺼﻞ اﻋﺪاد ﻣﺮﺗﺒﺔ ﺣﺴﺐ ﻣﺌﺎﺗﻬﺎ ....اﻟﺦ. ﻣﺜﺎل -:رﺗﺐ ﻋﻨﺎﺻﺮ اﻟﻘﺎﺋﻤﺔ اﻟﺘﺎﻟﻴﺔ ﺑﺎﺳﺘﺨﺪام ﻃﺮﻳﻘﺔ اﻟﺘﺮﺗﻴﺐ ﺑﺎﺳﺘﺨﺪام اﻻﺳﺎس اﻟﻌﺸﺮي 5
66
93
17
41
54
11
43
ﺧﻄﻮات اﻟﺤﻞ-: اﻟﻘﺎﺋﻤﺔ
اﻟﻤﺮﺣﻠﺔ 1
ﻣﻠﻒ اﻻﺣﺎد
اﻟﻘﺎﺋﻤﺔ ﺑﻌﺪ
ﻣﻠﻒ
اﻟﻤﺮﺣﻠﺔ 1
اﻟﻌﺸﺮات
اﻟﻤﺮﺣﻠﺔ 2
اﻟﻘﺎﺋﻤﺔ ﺑﻌﺪ اﻟﻤﺮﺣﻠﺔ2
66
0
ﻻﻳﻮﺟﺪ
41
0
5
5
5
1
11,41
11
1
11,17
11
17
2
ﻻﻳﻮﺟﺪ
43
2
ﻻﻳﻮﺟﺪ
17
93
3
93,43
93
3
ﻻﻳﻮﺟﺪ
41
41
4
54
54
4
41,43
43
11
5
5
5
5
54
54
54
6
66
66
6
66
66
43
7
17
17
7
ﻻﻳﻮﺟﺪ
93
54
8
ﻻﻳﻮﺟﺪ
8
ﻻﻳﻮﺟﺪ
43
9
ﻻﻳﻮﺟﺪ
9
93
Balanced two-way Merge Algorithm ﺧﻮارزﻣﻴﺔ اﻟﺪﻣﺞ اﻟﻤﺘﻮازي ذي اﻟﻤﺴﺎرﻳﻦ ﻓﻜﺮﺗﻬﺎ-: .1ﺗﻘﺴﻴﻢ اﻟﻘﺎﺋﻤﺔ اﻻﺻﻠﻴﺔ اﻟﻰ ﻗﺎﺋﻤﺘﻴﻦ ﻣﺘﺴﺎوﻳﺘﻴﻦ ﺗﻘﺮﻳﺒًﺎ وﻟﺘﻜﻦ .2ﻧﻘﺎرن اﻟﻌﻨﺼﺮ اﻻول ﻣﻦ اﻟﻘﺎﺋﻤﺔ A
. A,B
ﻣﻊ ﻧﻈﺮﻳﻪ ﻣﻦ اﻟﻘﺎﺋﻤﺔ اﻟﺜﺎﻧﻴﺔ Bوﻧﻀﻌﻬﺎ ﺑﺎﻟﺘﺮﺗﻴﺐ ﻓﻲ اﻟﻘﺎﺋﻤﺔ C
.3ﻧﻘﺎرن اﻟﻌﻨﺼﺮ اﻟﺜﺎﻧﻲ ﻣﻦ اﻟﻘﺎﺋﻤﺔ Aﻣﻊ ﻧﻈﺮﻳﻪ ﻣﻦ اﻟﻘﺎﺋﻤﺔ اﻟﺜﺎﻧﻴﺔ Bوﻧﻀﻌﻬﺎ ﺑﺎﻟﺘﺮﺗﻴﺐ ﻓﻲ اﻟﻘﺎﺋﻤﺔ D 2
.4ﻧﻜﺮر اﻟﺨﻄﻮات 2,3وﻧﺤﺼﻞ ﻋﻠﻰ ﻋﻨﺎﺻﺮ ﺑﻄﻮل 2ﻓﻲ اﻟﻘﺎﺋﻤﺘﻴﻦ
. C,D
.5ﺑﻨﻔﺲ اﻟﻄﺮﻳﻘﺔ ﻧﺪﻣﺞ ﻋﻨﺎﺻﺮ اﻟﻘﺎﺋﻤﺘﻴﻦ C,Dﻟﻨﺤﺼﻞ ﻋﻠﻰ ﻋﻨﺎﺻﺮ ﺑﻄﻮل 4ﻓﻲ اﻟﻘﺎﺋﻤﺘﻴﻦ
A,B
.6ﺑﻨﻔﺲ اﻟﻄﺮﻳﻘﺔ ﻧﻘﻮم ﺑﺪﻣﺞ ﻋﻨﺎﺻﺮ اﻟﻘﺎﺋﻤﺘﻴﻦ A,Bﻟﻨﺤﺼﻞ ﻋﻠﻰ ﻋﻨﺎﺻﺮ ﺑﻄﻮل ﺛﻤﺎﻧﻴﺔ. .7ﻧﺴﺘﻤﺮ ﺑﻬﺬا اﻻﺳﻠﻮب ﻟﺤﻴﻦ اﻟﺤﺼﻮل ﻋﻠﻰ ﻗﺎﺋﻤﺔ ﻣﺮﺗﺒﺔ. وهﻲ اﺣﺪ ﻃﺮق اﻟﺘﺮﺗﻴﺐ اﻟﺨﺎرﺟﻲ . ﻣﺜﺎل -:رﺗﺐ ﻋﻨﺎﺻﺮ اﻟﻘﺎﺋﻤﺔ اﻟﺘﺎﻟﻴﺔ ﺑﺎﺳﺘﺨﺪام ﻃﺮﻳﻘﺔ اﻟﺪﻣﺞ اﻟﻤﺘﻮازي ذي اﻟﻤﺴﺎرﻳﻦ 66
5
17
93
41
11
54
43
ﺧﻄﻮات اﻟﺤﻞ-: A: 43, 54, 11, 41 B: 93, 17, 5, 66
C: 43, 93, 5, 11 D: 17,54, 41,66
A: 17, 43,54, 93 B: 5,11, 41, 66
C: 5,11,17,41,43,54,66,93
3