1729172959-UNIT-V Internal Sorting
1729172959-UNIT-V Internal Sorting
Class : II B.Sc. CS
Semester : III
procedure SEQSRCH(F,n,i,K)
//Search a file F with key values K1, ...,Kn for a record Ri such that
Ki = K. If there is no such record, i is set to 0//
K0← K; i ← n;
while Ki ≠ K do
i←i-1
end
end SEQSRCH
Methods of Sorting
• To begin with we characterize sorting methods into two broad
categories:
(i) internal methods, i.e., methods to be used when the file to be
sorted is small enough so that the entire sort can be carried out in
main memory; and
(ii) external methods, i.e., methods to be used on larger files. The
following internal sorting
methods:
a) Insertion sort
b) Quick sort
c) Merge sort
d) Heap sort
e) Radix sort
INSERTION SORT
procedure INSORT(R,n)
//sort the records R1, ...,Rn in nondecreasing value of the key K. Assume n > 1//
Ko - //Create a dummy record Ro such that Ko < Ki, 1 i n//
for j 2 to n do
T Rj
call INSERT(T, j - 1) //insert records R2 to Rn//
end
end INSORT
Example: Assume n = 5 and the input sequence
is (5,4,3,2,1). Then, after each insertion we have
the following.
•- , 5, 4, 3, 2, 1 [initial sequence]
•- , 4, 5, 3, 2, 1 i=2
•- , 3, 4, 5, 2, 1 i=3
•- , 2, 3, 4, 5, 1 i=4
•- , 1, 2, 3, 4, 5 i=5
THANK YOU
Department of Computer Science
Class : II B.Sc. CS
Semester : III
Class : II B.Sc. CS
Semester : III
//(Xl, ...,Xm) and (Xm+1, ...,Xn) are two sorted files with keys xl≤... ≤xm and Xm+1 ≤ ... ≤xn.
They are merged to obtain the sorted file (Zl, ..., Zn) such that zl≤ ... ≤zn// i🡨 k🡨 l; j🡨 m +
1 //i, j and k are position in the three files//
While i≤ m and j≤n do
if xi ≤xj then [Zk🡨 Xi; i🡨 i+ 1]
else [Zk🡨 Xj; j 🡨 j+ 1] k🡨 k + 1
end
if i>m then (Zk, ...,Zn) 🡨 (Xj, ...,Xn)
else (Zk, ...,Zn) 🡨 (Xi ...,Xm)
end MERGE
Example1 :
• The input file is (26, 5, 77, 1, 61, 11, 59, 15, 15, 48, 19). The tree below illustrates the subfiles
being merged at each pass:
Example
Example
Department of Computer Science
Class : II B.Sc. CS
Semester : III
• R←Ri; K ← Ki; j ← 2i
• while j ≤n do
• if j<n and Kj <Kj+1 then j ← j + 1 //find max of left and right child//
• //compare max. child with K. If K is max. then done//
• if K ≥ Kj then[R j/2 ← R; return]
• R j/2 ← Rj; j ← 2j //move Rj up the tree//
• end
• R j/2 ← R
• end ADJUST
Example1
• The input file is (26, 5, 77, 1, 61, 11, 59, 15, 48, 19). Interpreting this as a
binary tree we have the following transformations: