You are on page 1of 23

Thut Ton Sp Xp

Trong khoa hc my tnh v trong ton hc, mt thut ton sp xp l mt thut ton sp xp
cc phn t ca mt danh sch (hoc mt mng theo th t (tng hoc gim)). Ngi ta thng
xt trng hp cc phn t cn sp xp l cc s.
Bi ton sp xp c nhiu nh khoa hc quan tm.

I.Phn loi thut ton sp xp


1.Sp xp n nh

Mt thut ton sp xp c gi l sp xp n nh nu sau khi tin hnh sp xp v tr tng i


gia cc phn t bng nhau khng b thay i.
2.Sp xp so snh

Mt thut ton sp xp c gi l sp xp so snh nu trong qu trnh thc hin thut ton ta


tin hnh so snh cc kho v i ch cc phn t cho nhau. a s cc thut ton sp xp di
y l sp xp so snh, ring sp xp m phn phi khng phi l sp xp so snh.

II.Mt s thut ton sp xp


1.Sp xp ni bt

Sp xp ni bt (bubble sort) l phng php sp xp n gin, d hiu thng c dy trong


khoa hc my tnh. Gii thut bt u t u ca tp d liu. N so snh hai phn t u, nu
phn t ng trc ln hn phn t ng sau th i ch chng cho nhau. Tip tc lm nh vy
vi cp phn t tip theo cho n cui tp hp d liu. Sau n quay li vi hai phn t u
cho n khi khng cn cn phi i ch na.
2.Sp xp chn

Sp xp chn (insertion sort) l mt thut ton sp xp rt hiu qu vi cc danh sch nh. N


ln lt ly cc phn t ca danh sch chn vo v tr thch hp trong mt danh sch mi c
sp.
3.Sp xp chn

Sp xp chn (selection sort) l phng php sp xp bng cch chn phn t b nht xp vo v
tr th nht, tng t vi cc phn t nh t
4.Sp xp trn

Sp xp trn (merge sort) cng vi sp xp nhanh l hai thut ton sp xp da vo t tng


"chia tr" (divide and conquer). Th tc c bn l vic trn hai danh sch c sp xp vo
mt danh sch mi theo th t. N c th bt u trn bng cch so snh hai phn t mt (chng

hn phn t th nht vi phn t th hai, sau th ba vi th t...) v sau khi kt thc bc 1


n chuyn sang bc 2. bc 2 n trn cc danh sch hai phn t thnh cc danh sch bn
phn t. C nh vy cho n khi hai danh sch cui cng c trn thnh mt.
5.Sp xp vun ng

Sp xp vun ng(heapsort) l mt trong cc phng php sp xp chn. mi bc ca sp


xp chn ta chn phn t ln nht (hoc nh nht) t vo cui (hoc u) danh sch, sau tip
tc vi phn cn li ca danh sch. Thng thng sp xp chn chy trong thi gian O(n2).
Nhng heapsort gim phc tp ny bng cch s dng mt cu trc d liu c bit c
gi l ng (heap). ng l cy nh phn m trng s mi nh cha ln hn hoc bng trng s
cc nh con ca n. Mt khi danh sch d liu c vun thnh ng, gc ca n l phn t
ln nht, thut ton s gii phng n khi ng t vo cui danh sch. Sp xp vun ng
chy trong thi gian O(n log n).
6.Sp xp nhanh

Sp xp nhanh (quicksort) l mt thut ton theo t tng chia tr, n da trn th tc phn
chia nh sau: chia mt dy ta chn mt phn t c gi l "cht" (pivot), chuyn tt c cc
phn t nh hn cht v trc cht, chuyn tt c cc phn t ln hn cht v sau n. Th tc
ny c th thc hin trong thi gian tuyn tnh. Tip tc phn chia cc dy con nh trn cho
n khi cc dy con ch cn mt phn t.
im khc bit gia sp xp nhanh v sp xp trn l trong sp xp trn vic xc nh th t
c xc nh khi "trn", tc l trong khu tng hp li gii sau khi cc bi ton con c
gii, cn sp xp nhanh quan tm n th t cc phn t khi phn chia mt danh sch thnh
hai danh sch con.
Ngoi ra cn nhiu gii thut sp xp khc, trong nhiu gii thut sp xp c ci tin t cc
gii thut trn. Trong sau gii thut lit k trn, ta thng coi cc gii thut chn, chn, ni bt l
cc gii thut c bn, phc tp trong trng hp trung bnh ca chng l O(n2). Ba gii thut
cn li thng c coi l gii thut cao cp, phc tp tnh ton trung bnh ca chng l n.lnn.
7.Sp xp theo c s

Sp xp theo c s (radix sort) da trn tnh cht "s" ca cc kha. Trong gii thut sp xp
theo c s, ta khng ch so snh gi tr ca cc kha, m so snh cc thnh phn ca kha. Gi s
cc kha l cc s biu din theo h ghi s c s M. Khi sp xp theo c s s so snh tng k
s ca n.
Chng ta m t cch sp ny khi c s M=10. Gi s phi sp cc h s nh s bi 3 ch s
thp phn. u tin ta chia cc h s vo cc ng c cng ch s hng trm (ng thi xp cc
ng theo th t ca ch s hng trm), trong mi ng con li phn chia theo ch s hng chc,

cui cng trong mi ng c cng ch s hng trm v hng chc, sp xp theo th t ca ch


s hng n v.
Trong my tnh, ng nhin vic sp xp theo c s nh phn (c s 2) hoc c s l ly tha
ca 2 l thun li nht. Trong trng hp c s 2, vic phn hoch tng t nh phn hoch
trong Quick Sort, ch khc ch cch chn phn t chtmn
8.Sp xp m phn phi

Sp xp m phn phi l phng php sp xp c phc tp tuyn tnh trong trng hp cc


kha nhn hu hn gi tr trong khong cho trc. n gin ta gi s cc phn t ca danh
sch a[1..n] nhn cc gi tr t nhin trong khong [1..M].
Sp xp m phn phi u tin m cc phn t thuc danh sch nhn gi tr k vi
. Cc gi tr m c c ghi vo mng Counter[1..M]. Sau khi duyt theo
k t 1 n M, ta ln lt xp Counter[k] phn t ca vo danh sch a[1..n].

Bi 1:

Sp xp chn(Selection Sort)

1.T tng
Chn phn t nh nht trong n phn t ban u, a phn t ny v v tr ng l u tin ca
dy hin hnh. Sau khng quan tm n n na, xem dy hin hnh ch cn n-1 phn t ca
dy ban u, bt u t v tr th 2. Lp li qu trnh trn cho dy hin hnh n khi dy hin
hnh ch cn 1 phn t. Dy ban u c n phn t, vy tm tt tng thut ton l thc hin n-1
lt vic a phn t nh nht trong dy hin hnh v v tr ng u dy.
Phc tp thi gian: Trung bnh O(n2).
Phc tp d liu: Khng tn thm vng nh.
Cc bc tin hnh nh sau:
Bc 1: i=1
Bc 2: Tm phn t a[min] nh nht trong dy hin hnh t a[i] n a[n]
Bc 3: Hon v a[min] v a[i]
Bc 4: Nu i<=n-1 th i=i+1; Lp li bc 2
Ngc li: Dng. n-1 phn t nm ng v tr.

V d: Cho dy a = (12,2,8,5,1,6,4,15)
12 2 8 5 1 6 4 15
Bc 1: 1 2 8 5 12 6 4 15
Bc 2: 1 2 8 5 12 6 4 15
Bc 3: 1 2 4 5 12 6 8 15
Bc 4: 1 2 4 5 12 6 8 15
Bc 5: 1 2 4 5 6 12 8 15
Bc 6: 1 2 4 5 6 8 12 15
Bc 7: 1 2 4 5 6 8 12 15

2.Gii thut
Void SelectionSort(int a[], int n)
{
int min;
for(int i=0;i<n-1;i++)
{
min=i;
for(int j=i+1;j<n;j++)
if(a[j]<a[min]) min=j;
HoanVi(a[min],a[i]);
}
}

3.Ci t bng Java:


3.1.Lp SelectionSort
1
2
3
4
5
6
7
8
9
10
11
12

// Fig 16.6: SelectionSort.java


// Class that creates an array filled with random integers.
// Provides a method to sort the array with selection sort.
import java.util.Random;
public class SelectionSort
{
private int [] data; // array of values
private static Random generator = new Random();
// create array of given size and fill with random integers
public SelectionSort( int size )

13
{
14
data = new int [ size ]; // create space for array
15
16
// fill array with random ints in range 10-99
17
for ( int i = 0; i < size; i++ )
18
data[ i ] = 10 + generator.nextInt( 90 );
19
} // end SelectionSort constructor
20
21
// sort array using selection sort
22
public void sort()
23
{
24
int smallest; // index of smallest element
25
26
// loop over data.length - 1 elements
27
for ( int i = 0 ; i < data.length - 1 ; i++ )
28
{
29
smallest = i; // first index of remaining array
30
31
// loop to find index of smallest element
32
for ( int index = i + 1 ; index < data.length; index++ )
33
if ( data[ index ] < data[ smallest ] )
34
smallest = index;
35
36
swap( i, smallest ); // swap smallest element into
position
37
printPass( i + 1, smallest ); // output pass of algorithm
38
} // end outer for
39
} // end method sort
40
41
// helper method to swap values in two elements
42
public void swap( int first, int second )
43
{
44
int temporary = data[ first ]; // store first in temporary
45
data[ first ] = data[ second ]; // replace first with second
46
data[ second ] = temporary; // put temporary in second
47
} // end method swap
48
49
// print a pass of the algorithm
50
public void printPass( int pass, int index )
51
{
52
System.out.print( String.format( "after pass %2d: ",
pass ) );
53
54
// output elements till selected item
55
for ( int i = 0 ; i < index; i++ )
56
System.out.print( data[ i ] + " " );
57
58
System.out.print( data[ index ] + "* " ); // indicate swap
59
60
// finish outputting array
61
for ( int i = index + 1; i < data.length; i++ )
62
System.out.print( data[ i ] + " " );

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

System.out.print( "\n

" ); // for alignment

// indicate amount of array that is sorted


for ( int j = 0 ; j < pass; j++ )
System.out.print( "-" );
System.out.println( "\n" ); // add endline
} // end method indicateSelection
// method to output values in array
public String toString()
{
StringBuffer temporary = new StringBuffer();
// iterate through array
for ( int element : data )
temporary.append( element + "

" );

temporary.append( "\n" ); // add endline character


return temporary.toString();
} // end method toString
} // end class SelectionSort

3.2.Xy dng lp SelectionSortTest


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// Fig 16.7: SelectionSortTest.java


// Test the selection sort class.
public class SelectionSortTest
{
public static void main( String[] args )
{
// create object to perform selection sort
SelectionSort sortArray = new SelectionSort( 10 );
System.out.println( "Unsorted array:" );
System.out.println( sortArray ); // print unsorted array
sortArray.sort(); // sort array
System.out.println( "Sorted array:" );
System.out.println( sortArray ); // print sorted array
} // end main
} // end class SelectionSortTest

Kt qu:

Unsorted array:
61 87 80 58 40 50 20 13 71 45
after pass 1: 13 87 80 58 40 50 20 61* 71 45
-after pass 2: 13 20 80 58 40 50 87* 61 71 45
-- -after pass 3: 13 20 40 58 80* 50 87 61 71 45
-- -- -after pass 4: 13 20 40 45 80 50 87 61 71 58*
-- -- -- -after pass 5: 13 20 40 45 50 80* 87 61 71 58
-- -- -- -- -after pass 6: 13 20 40 45 50 58 87 61 71 80*
-- -- -- -- -- -after pass 7: 13 20 40 45 50 58 61 87* 71 80
-- -- -- -- -- -- -after pass 8: 13 20 40 45 50 58 61 71 87* 80
-- -- -- -- -- -- -- -after pass 9: 13 20 40 45 50 58 61 71 80 87*
-- -- -- -- -- -- -- -- -Sorted array:
13 20 40 45 50 58 61 71 80 87

Bi 2:

Sp Xp Chn(Inserion Sort)

Sp xp chn (insertion sort) l mt thut ton sp xp bt chc cch sp xp qun bi ca

nhng ngi chi bi. Mun sp mt b bi theo trt t ngi chi bi rt ln lt t qun th 2,
so vi cc qun ng trc n chn vo v tr thch hp.
Phc tp thi gian: Trung bnh O(n2).
Phc tp d liu: Khng tn thm vng nh.

1.T tng
C s lp lun ca sp xp chn c th m t nh sau: Xt danh sch con gm k phn t u
a1,...,ak. Vi k = 1, danh sch gm mt phn t c sp. Gi s trong danh sch k-1 phn t
u a1,...,ak 1 c sp. sp xp phn t ak = x ta tm v tr thch hp ca n trong dy
a1,...,ak 1. V tr thch hp l ng trc phn t ln hn n v sau phn t nh hn hoc bng
n.
Cc phn t x

V tr thch hp

Cc phn t>x

Cc phn t cha sp

a1

ai + 1

ak + 1

...

ai 1

...

ak 1

...

an

V d
Cho danh sch
1

Danh sch con gm 3 phn t bn tri 1,3,7 c sp. tip tc sp xp phn t th t a4 =


6 vo danh sch con , ta tm v tr thch hp ca n l sau 3 v trc 7.
1

Lm tip theo vi a5 = 4 ta c
1

Lm tip theo vi a6 = 2 ta c
1

Cui cng chn a7 = 5


1

2.Gii thut

Danh sch a bt u t ch s 1 ti length

Procedure Insert (array a, int k, Value) {


int i := k-1;
while (i > 0 and a[i] > value) {
a[i+1] := a[i];
i := i - 1;
}
a[i+1] := value;
}
Procedure InsertSort (array a, int length) {
int k := 2;
while (k <= length) {
insert(a, k, a[k]);
k := k + 1;
}
}

3.Ci t bng Java


3.1.Lp InsertionSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

// Fig 16.8: InsertionSort.java


// Class that creates an array filled with random integers.
// Provides a method to sort the array with insertion sort.
import java.util.Random;
public class InsertionSort
{
private int[] data; // array of values
private static Random generator = new Random();
// create array of given size and fill with random integers
public InsertionSort( int size )
{
data = new int [ size ]; // create space for array
// fill array with random ints in range 10-99
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
} // end InsertionSort constructor
// sort array using insertion sort
public void sort()
{
int insert; // temporary variable to hold element to insert
// loop over data.length - 1 elements
for ( int next = 1; next < data.length; next++ )
{
// store value in current element
insert = data[ next ];
// initialize location to place element
int moveItem = next;

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

// search for place to put current element


while ( moveItem > 0 && data[ moveItem - 1 ] > insert )
{
// shift element right one slot
data[ moveItem ] = data[ moveItem - 1 ];
moveItem--;
} // end while
data[ moveItem ] = insert; // place inserted element
printPass( next, moveItem ); // output pass of algorithm
} // end for
} // end method sort
// print a pass of the algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ", pass ) );
// output elements till swapped item
for ( int i = 0 ; i < index; i++ )
System.out.print( data[ i ] + " " );
System.out.print( data[ index ] + "* " ); // indicate swap
// finish outputting array
for ( int i = index + 1; i < data.length; i++ )
System.out.print( data[ i ] + " " );
System.out.print( "\n

// indicate amount of array that is sorted


for( int i = 0; i <= pass; i++ )
System.out.print( "-- " );
System.out.println( "\n" ); // add endline
} // end method printPass
// method to output values in array
public String toString()
{
StringBuffer temporary = new StringBuffer();
// iterate through array
for ( int element : data )
temporary.append( element + "

2
3

" );

temporary.append( "\n" ); // add endline character


return temporary.toString();
} // end method toString
} // end class InsertionSort

3.2.Lp InsertionSortTest
1

" ); // for alignment

// Fig 16.9: InsertionSortTest.java


// Test the insertion sort class.

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

public class InsertionSortTest


{
public static void main( String[] args )
{
// create object to perform selection sort
InsertionSort sortArray = new InsertionSort( 10 );
System.out.println( "Unsorted array:" );
System.out.println( sortArray ); // print unsorted array
sortArray.sort(); // sort array
System.out.println( "Sorted array:" );
System.out.println( sortArray ); // print sorted array
} // end main
} // end class InsertionSortTest

Kt qu
Unsorted array:
40 17 45 82 62 32 30 44 93 10
after pass 1: 17* 40 45 82 62 32 30 44 93 10
-- -after pass 2: 17 40 45* 82 62 32 30 44 93 10
-- -- -after pass 3: 17 40 45 82* 62 32 30 44 93 10
-- -- -- -after pass 4: 17 40 45 62* 82 32 30 44 93 10
-- -- -- -- -after pass 5: 17 32* 40 45 62 82 30 44 93 10
-- -- -- -- -- -after pass 6: 17 30* 32 40 45 62 82 44 93 10
-- -- -- -- -- -- -after pass 7: 17 30 32 40 44* 45 62 82 93 10
-- -- -- -- -- -- -- -after pass 8: 17 30 32 40 44 45 62 82 93* 10
-- -- -- -- -- -- -- -- -after pass 9: 10* 17 30 32 40 44 45 62 82 93
-- -- -- -- -- -- -- -- -- -Sorted array:
10 17 30 32 40 44 45 62 82 93

Sp Xp Trn(Merge Sort)

Trong khoa hc my tnh, sp xp trn (merge sort) l mt thut ton sp xp sp xp cc


danh sch (hoc bt k cu trc d liu no c th truy cp tun t, v.d. lung tp tin) theo mt
trt t no . Thut ton ny l mt v d tng i in hnh ca li thut ton chia tr. N
c xp vo th loi sp xp so snh.

1.Trn
Gi s c hai danh sch c sp xp a[1..m] v b[1..n.]. Ta c th trn chng li thnh mt
danh sch mi c[1..m + n] c sp xp theo cch sau:

So snh hai phn t ng u ca hai danh sch, ly phn t nh hn cho


vo danh sch mi. Tip tc nh vy cho ti khi mt trong hai danh sch l
rng.

Khi mt trong hai danh sch l rng ta ly phn cn li ca danh sch kia cho
vo cui danh sch mi.

V d: Cho hai danh sch a = (1,3,7,9),b = (2,6), qu trnh ha nhp din ra nh sau:
Danh sch a

Danh sch b

So snh

1,3,7,9

2,6

1<2

3,7,9

2,6

2<3

1,2

3,7,9

3<6

1,2,3

7,9

6<7

1,2,3,6

7,9

Danh sch c

1,2,3,6,7,9

2.Trn ti ch
Gi s trong danh sch a[1..n] c 2 danh sch con k nhau a[k1..k2] v a[k2 + 1..k3] c sp.
Ta p dng cch trn tng t nh trn trn hai danh sch con vo mt danh sch tm T[k1..k3]
ri tr li cc gi tr ca danh sch tm T v danh sch A. Lm nh vy gi l trn ti ch.

3.Trn t di ln
Nu danh sch con ch gm hai phn t, mi na ca n gm mt phn t ng nhin c
sp. Do vic trn ti ch hai na danh sch ny cho danh sch con 2 phn t c sp.
Xut pht t u danh sch a ta trn a[1] vi a[2], a[3] vi a[4],... Khi mi danh sch con
gm hai phn t ca a c sp. Tip tc trn cc danh sch con k tip nhau gm 2 phn t
thnh cc danh sch con 4 phn t ... Mi ln trn s cc danh sch con cn trn gim i mt
na. Qu trnh dng li khi s danh sch con ch cn mt.

V d: Cho danh sch a = (2,3,5,6,4,1,7)


Cng vic

S DS con

Kt qu

Trn cc phn t ng k nhau

2,3-5,6-1,4-7

Trn cc danh sch con 2 phn t k nhau

2,3,5,6-1,4,7

Trn cc danh sch con 4 phn t k nhau

1,2,3,4,5,6,7

4.Sp xp trn quy


Mt cch gi quy ca sp xp trn cng thng c hng dn trong cc gio trnh gii
thut.
sp xp trn on a[k1..k2] ca danh sch a[1..n] ta chia on thnh 2 phn a[k1..k3] v a[k3
+ 1..k2],trong k3 = int((k1 + k2) / 2) tin hnh sp xp vi mi phn ri trn chng li. Li gi
th tc sp xp trn vi a[1..n] s cho kt qu l sp ton b danh sch a[1..n]
V d: Cho danh sch a = [2,7,6,3,4,5,1]
Gii thut trn quy chia a thnh hai danh sch con v tin hnh 3 bc

Danh sch tri

Danh sch phi

2,7,6

3,4,5,1

Sp xp trn danh sch tri 2,7,6

Qu trnh chia

Qu trnh trn

2,7,6

2,6,7

7,6

6,7

Sp xp trn danh sch phi 3,4,5,1

Qu trnh chia

Qu trnh trn

3,4,5,1

1,3,4,5

3,4

5,1

3,4

1,5
4

Trn danh sch tri 2,6,7 vi danh sch phi 1,3,4,5

Danh sch tri

Danh sch phi

Danh sch trn

2,6,7

1,3,4,5

1,2,3,4,5,6,7

5.Trn cc ng t nhin
Nh trong phn nh gi gii thut, mt trong nhng nhc im ln ca thut ton Trn trc
tip l khng tn dng nhng thng tin v c tnh ca dy cn sp xp. V d trng hp dy
c th t sn. Chnh v vy, trong thc t ngi ta t dng thut ton trn trc tip m ngi ta
dng phin bn ci tin ca n. Phin bn ny thng c bit vi tn gi thut ton trn t
nhin (Natural Merge sort).
5.1.Khi nim ng chy

kho st thut ton trn t nhin, trc tin ta cn nh ngha khi nim ng chy (run):
Mt ng chy ca dy s a l mt dy con khng gim ca cc i ca a.
Ngha l, ng chy r = (ai, ai+1, ..., aj) phi tha iu kin:

0 i j < n , vi n l s phn t ca dy a

ak ak+1 k, i k j
V d dy 12, 2, 8, 5, 1, 6, 4, 15 c th coi nh gm 5 ng chy (12); (2, 8);
(5); (1, 6); (4, 15).

5.2.Gii thut

Cc bc thc hin thut ton trn t nhin nh sau:

Bc 1 : // Chun b
r = 0; // r dng m s dng chy

Bc 2 :
Tch dy a1, a2, ..., an thnh 2 dy b, c theo nguyn tc lun phin tng ng
chy:

Bc 2.1 :

Phn phi cho b mt ng chy; r = r+1;


Nu a cn phn t cha phn phi
Phn phi cho c mt ng chy; r = r+1;

Bc 2.2 :

Nu a cn phn t: quay li bc 2.1;

Bc 3 :
Trn tng cp ng chy ca 2 dy b, c vo a.

Bc 4 :
Nu r <= 2 th tr li bc 2;
Ngc li: Dng;

5.3.u v nhc im

Thut ton trn t nhin khc thut ton trn trc tip ch thay v lun cng nhc phn
hoch theo dy con c chiu di k, vic phn hoch s theo n v l ng chy. ta ch
cn bit s ng chy ca a sau ln phn hoch cui cng l c th bit thi im dng
ca thut ton v dy c th t l dy chi c mt ng chy.

Mt nhc im ln na ca thut ton trn l khi ci t thut ton i hi thm khng


gian b nh lu cc dy ph b, c. Hn ch ny kh chp nhn trong thc t v cc dy
cn sp xp thng c kch thc ln. V vy thut ton trn thng c dng sp
xp cc cu trc d liu khc ph hp hn nh danh sch lin kt hoc file.

6.Gii thut
6.1.Trn
Procedure Merge(a,k1,k2,k3)
Var Int i,j,k
List T[k1..k3]
{
i=k1
j=k2
k=k1
while i<k2 and j<=k3
{
if a[i]<=a[j] then {
T[k]=a[i]
i=i+1
}
else {

T[k]=a[j]
j=j+1
}
k=k+1
}
if i>=k2 then
while k<=k3 {
T(k)=a[j]
j=j+1
k=k+1
}
if j>k3 then
while k<k2 {
T(k)=a[i]
i=i+1
k=k+1
}
For k=k1 to k3
a[k]=T[k]

6.2.Trn t di ln
Procedure MergeSortUp (a[1..n)
Var Int m,i
{
m=1
while m<n {
k=0
while k+m<=n {
merge(a,k+1,k+m+1,k+2m)
k=k+2m
}
}
m=2*m
}

6.3.Trn quy
Procedure MergeSort (a,k1,k2)
Var Int k3
{
if k1<k2 then {
k3=int((k1+k2)/2)
MergeSort(a,k1,k3)
MergeSort(a,k3+1,k2)

Merge(a,k1,k3+1,k2)
}

7.Ci t bng Java


7.1.Lp MergeSort
1 // Figure 16.10: MergeSort.java
2 // Class that creates an array filled with random integers.
3 // Provides a method to sort the array with merge sort.
4 import java.util.Random;
5
6 public class MergeSort
7 {
8
private int [] data; // array of values
9
private static Random generator = new Random();
10
11
// create array of given size and fill with random integers
12
public MergeSort( int size )
13
{
14
data = new int [ size ]; // create space for array
15
16
// fill array with random ints in range 10-99
17
for ( int i = 0 ; i < size; i++ )
18
data[ i ] = 10 + generator.nextInt( 90 );
19
} // end MergeSort constructor
20
21
// calls recursive split method to begin merge sorting
22
public void sort()
23
{
24
sortArray( 0, data.length - 1 ); // split entire array
25
} // end method sort
26
27
// splits array, sorts subarrays and merges subarrays into sorted
array
28
private void sortArray( int low, int high )
29
{
30
// test base case; size of array equals 1
31
if ( ( high - low ) >= 1 ) // if not base case
32
{
33
int middle1 = ( low + high ) / 2; // calculate middle of array
34
int middle2 = middle1 + 1; // calculate next element over
35
36
// output split step
37
System.out.println( "split:
" + subarray( low, high ) );
38
System.out.println( "
" + subarray( low, middle1 );
39
System.out.println( "
" + subarray( middle2, high ) );
40
System.out.println();
41
42
// split array in half; sort each half (recursive calls)
43
sortArray( low, middle1 ); // first half of array
44
sortArray( middle2, high ); // second half of array
45
46
// merge two sorted arrays after split calls return
47
merge ( low, middle1, middle2, high );
48
} // end if
49
} // end method split
50
51
// merge two sorted subarrays into one sorted subarray

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

private void merge( int left, int middle1, int middle2, int right )
{
int leftIndex = left; // index into left subarray
int rightIndex = middle2; // index into right subarray
int combinedIndex = left; // index into temporary working array
int [] combined = new int [ data.length ]; // working array
// output two subarrays before merging
System.out.println( "merge:
" + subarray( left, middle1 ) );
System.out.println( "
" + subarray( middle2, right ) );
// merge arrays until reaching end of either
while ( leftIndex <= middle1 && rightIndex <= right )
{
// place smaller of two current elements into result
// and move to next space in arrays
if ( data[ leftIndex ] <= data[ rightIndex ] )
combined[ combinedIndex++ ] = data[ leftIndex++ ];
else
combined[ combinedIndex++ ] = data[ rightIndex++ ];
} // end while
// if left array is empty
if ( leftIndex == middle2 )
// copy in rest of right array
while ( rightIndex <= right )
combined[ combinedIndex++ ] = data[ rightIndex++ ];
else // right array is empty
// copy in rest of left array
while ( leftIndex <= middle1 )
combined[ combinedIndex++ ] = data[ leftIndex++ ];
// copy values back into original array
for ( int i = left; i <= right; i++ )
data[ i ] = combined[ i ];
// output merged array
System.out.println( "
System.out.println();
} // end method merge

" + subarray( left, right ) );

// method to output certain values in array


public String subarray( int low, int high )
{
StringBuffer temporary = new StringBuffer();
// output spaces for alignment
for ( int i = 0; i < low; i++ )
temporary.append( "
" );
// output elements left in array
for ( int i = low; i <= high; i++ )
temporary.append( " " + data[ i ] );
return temporary.toString();
} // end method subarray

109
110
111
112
113
114

// method to output values in array


public String toString()
{
return subarray( 0, data.length - 1 );
} // end method toString
} // end class MergeSort

7.2.Lp MergeShortTest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// Figure 16.11: MergeSortTest.java


// Test the merge sort class.
public class MergeSortTest
{
public static void main( String[] args )
{
// create object to perform merge sort
MergeSort sortArray = new MergeSort( 10 );
// print unsorted array
System.out.println( "Unsorted:" + sortArray + "\n" );
sortArray.sort(); // sort array
// print sorted array
System.out.println( "Sorted:
} // end main
} // end class MergeSortTest

Kt qu

" + sortArray );

Unsorted: 75 56 85 90 49 26 12 48 40 47
split:

75 56 85 90 49 26 12 48 40 47
75 56 85 90 49
26 12 48 40 47

split:

75 56 85 90 49
75 56 85
90 49

split:

75 56 85
75 56
85

split:

75 56
75
56
75
56
56 75

merge:

merge:

56 75

85
56 75 85

split:

90 49
90
49

merge:

90

merge:

49
49 90
56 75 85

49 90
49 56 75 85 90

split:

26 12 48 40 47
26 12 48
40 47

split:

26 12 48
26 12
48

split:

26 12
26
12

merge:

26

merge:

12 26

12
12 26
48
12 26 48

Cc bi lin quan:

Sp Xp Ni Bt(Bubble Sort)
Sp xp ni bt (bubble sort) l mt thut ton sp xp n gin, vi thao tc c bn l so snh
hai phn t k nhau, nu chng cha ng ng th t th i ch (swap). C th tin hnh t
trn xung (bn tri sang) hoc t di ln (bn phi sang). Sp xp ni bt cn c tn l sp
xp bng so snh trc tip. N s dng php so snh cc phn t nn l mt gii thut sp xp
kiu so snh.
Phc tp thi gian: Trung bnh O(n2).
Phc tp d liu: Khng tn thm vng nh.

1.T tng
1.1.Sp xp t trn xung

V d:

Qu trnh sp xp ni bt ca 5 phn t
Gi s dy cn sp xp c n phn t. Khi tin hnh t trn xung, ta so snh hai phn t u, nu
phn t ng trc ln hn phn t ng sau th i ch chng cho nhau. Tip tc lm nh vy
vi cp phn t th hai v th ba v tip tc cho n cui tp hp d liu, ngha l so snh (v
i ch nu cn) phn t th n-1 vi phn t th n. Sau bc ny phn t cui cng chnh l
phn t ln nht ca dy. Sau , quay li so snh (v i ch nu cn) hai phn t u cho n
khi gp phn t th n-2....
Ghi ch: Nu trong mt ln duyt, khng phi i ch bt c cp phn t no th danh sch
c sp xp xong.
1.2.Sp xp t di ln

Sp xp t di ln so snh (v i ch nu cn) bt u t vic so snh cp phn t th n-1 v


n. Tip theo l so snh cp phn t th n-2 v n-1,... cho n khi so snh v i ch cp phn t

th nht v th hai. Sau bc ny phn t nh nht c ni ln vi tr trn cng (n ging


nh hnh nh ca cc "bt" kh nh hn c ni ln trn). Tip theo tin hnh vi cc phn t t
th 2 n th n.

2.Gii thut
2.1.Sp xp t trn xung
procedure bubble_sort1(list L, number n) //n=listsize
For number i from n downto 2
for number j from 1 to (n - 1)
if L[j] > L[j + 1] //nu chng khng ng th t
swap(L[j], L[j + 1]) //i ch chng cho nhau
endif
endfor
endfor
endprocedure
2.2.Sp xp t di ln
procedure bubble_sort2(list L, number n) //n=listsize
For' number i from 1 ' n-1
for number j from n-1 downto i
if L[j] > L[j + 1] //nu chng khng ng th t
swap(L[j], L[j + 1]) //i ch chng cho nhau
endif
endfor
endfor
endprocedure
2.3.Gim bt vng duyt

Nu trong mt ln duyt no vi mt i c nh khi vng lp j kt thc m khng cn phi di


ch cp phn t no, nghi l mi cp phn t k nhau ng ng th t th dy c sp
xp v khng cn tin hnh vng lp tip theo. Do c th dng mt c kim sot vic ny.
Ta c mt on m gi ca thut ton ni bt nh sau:
procedure bubble_sort3(list L, number n)
i:= n
while i > 1 do
has_swapped := 0 //khi to li gi tr c
for number j from 1 to (i - 1)
if L[j] > L[j + 1] //nu chng khng ng th t
swap(L[j], L[j + 1]) //i ch chng cho nhau
has_swapped := 1 //c i ch t nht mt ln, danh
sch cha sp xp xong
endif
endfor
if has_swapped = 0 //nu khng c ln i ch no, danh sch
sp xp xong
exit

xong

else //nu c t nht mt ln i ch, danh sch cha sp xp

i= i -1
endif
enddo
endprocedure

Ghi ch: Cng c th kng cn dng n bin i, khi mi ln kim tra u phi duyt t u
n cui dy.

3.Thi gian tnh


Vi mi i = 1,2, ..,n-1 ta cn i php so snh. Do s nhiu nht cc ln so snh v i ch trong
gii thut l

Do phc tp ca gii thut c O(n2) .

4. Ci t bng Java
private static void bubbleSort(int[] unsortedArray, int length) {
int temp, counter, index;

for(counter=0; counter<length-1; counter++) {


//Loop once for each element in the array.
for(index=0; index<length-1-counter; index++) {
//Once for each element, minus the counter.
if(unsortedArray[index] > unsortedArray[index+1]) {
//Test if need a swap or not.
temp = unsortedArray[index];
//These three lines just swap the two elements:
unsortedArray[index] = unsortedArray[index+1];
unsortedArray[index+1] = temp;
}
}
}

You might also like