Sei sulla pagina 1di 12

Page 1 of 12 QUICKSORT

{***************************************************************************** * A Pascal quicksort. *****************************************************************************} PROGRAM Sort(input, output); CONS { Ma! arra" si#$. } Ma!%lts & '(; )P% { "p$ o* t+$ $l$,$nt arra". } -ntArr "p$ & ARRA) ./..Ma!%lts0 O1 -nt$2$r; 3AR { -n4$!$s, $!c+an2$ t$,p, arra" si#$. } i, 5, t,p, si#$6 int$2$r; { Arra" o* ints } arr6 -ntArr "p$; { R$a4 in t+$ int$2$rs. } PROC%78R% R$a4Arr(3AR si#$6 -nt$2$r; 3AR a6 -ntArr "p$); 9%G-N si#$ 6& /; :;-<% NO $o* 7O 9%G-N r$a4ln(a.si#$0); -1 NO $o* ;%N si#$ 6& si#$ = / %N7 %N7; { 8s$ quicksort to sort t+$ arra" o* int$2$rs. } PROC%78R% >uicksort(si#$6 -nt$2$r; 3AR arr6 -ntArr "p$); { +is 4o$s t+$ actual ?ork o* t+$ quicksort. -t tak$s t+$ para,$t$rs ?+ic+ 4$*in$ t+$ ran2$ o* t+$ arra" to ?ork on, an4 r$*$r$nc$s t+$ arra" as a 2lo@al. } PROC%78R% >uicksortR$cur(start, stop6 int$2$r); 3AR ,6 int$2$r; { +$ location s$paratin2 t+$ +i2+ an4 lo? parts. } splitpt6 int$2$r; { +$ quicksort split al2orit+,. ak$s t+$ ran2$, an4 r$turns t+$ split point. } 18NC -ON Split(start, stop6 int$2$r)6 int$2$r; 3AR l$*t, ri2+t6 int$2$r; { Scan point$rs. } piAot6 int$2$r; { PiAot Aalu$. } { -nt$rc+an2$ t+$ para,$t$rs. } PROC%78R% s?ap(3AR a, @6 int$2$r); 3AR t6 int$2$r; 9%G-N t 6& a; a 6& @; @ 6& t %N7; 9%G-N { Split } { S$t up t+$ point$rs *or t+$ +i2+t an4 lo? s$ctions, an4 2$t t+$ piAot Aalu$. } piAot 6& arr.start0; l$*t 6& start = /; ri2+t 6& stop;

Page 2 of 12
{ <ook *or pairs out o* plac$ an4 s?ap B$,. } :;-<% l$*t C& ri2+t 7O 9%G-N :;-<% (l$*t C& stop) AN7 (arr.l$*t0 C piAot) 7O l$*t 6& l$*t = /; :;-<% (ri2+t D start) AN7 (arr.ri2+t0 D& piAot) 7O ri2+t 6& ri2+t E /; -1 l$*t C ri2+t ;%N s?ap(arr.l$*t0, arr.ri2+t0); %N7; { Put t+$ piAot @$t?$$n t+$ +alA$s. } s?ap(arr.start0, arr.ri2+t0); { %N7; +is is +o? "ou r$turn *unction Aalu$s in pascal. )$ccc+. } Split 6& ri2+t

9%G-N { >uicksortR$cur } { -* t+$r$Bs an"t+in2 to 4o... } -1 start C stop ;%N 9%G-N splitpt 6& Split(start, stop); >uicksortR$cur(start, splitptE/); >uicksortR$cur(splitpt=/, stop); %N7 %N7; 9%G-N { >uicksort } >uicksortR$cur(/, si#$) %N7; 9%G-N { R$a4 } R$a4Arr(si#$, arr); { Sort t+$ cont$nts. } >uicksort(si#$, arr); { Print. } 1OR i 6& / O si#$ 7O ?rit$ln(arr.i0) %N7.

Idea

Page 3 of 12

a is partitioned into two parts, such that all elements of the first part b are less than or equal to all elements of the second part c (divide). Then the two parts are sorted separately by recursive application of
First, the sequence to be sorted the same procedure (conquer). Recombination of the two parts yields the sorted sequence (combine). Figure illustrates this approach.

Figure ! "uic#sort(n)

The first step of the partition procedure is choosing a comparison element x. $ll elements of the sequence that are less than x are placed in the first part, all elements greater than to x remains between the two parts.

x are placed in the second part. For elements equal

to x it does not matter into which part they come. In the following algorithm it may also happen that an element equal

Algorithm Partition Input: Output: Method: sequence a%, ..., an& with n elements permutation of the sequence such that all elements a%, ..., aj are less than or equal to all elements ai, ..., an& (i ' j)

1.
while i

choose the element in the middle of the sequence as comparison element x let i ( % and j ( n&

j
search for the first element ai which is greater than or equal to x search for the last element aj which is less than or equal to x if i

1.
j

1.

e)change ai and aj let i ( i* and j ( j&

$fter partitioning the sequence, quic#sort treats the two parts recursively by the same procedure. The recursion ends whenever a part consists of one element only.

Page 4 of 12 STACKS AND QUEUES

STACKS A stack is used to provide temporary storage space for values. It is defined as a data structure which operates on a first in, last out basis. Its uses a single pointer (index) to keep track of the information in the stack. The basic operations associated with a stack are,

insert (push) an item onto the stack remove (pop) an item from the stack

The following diagram shows an empty stack of four locations. It looks ust like an array, and it has an index pointer pointing to the beginning of the stack (called the TOP of the stack). +--------+ | | <------- Stack Pointer +--------+ | | +--------+ | | +--------+ | | +--------+ Pushing items onto the stack The stack pointer is considered to be pointing to a free (empty) slot in the stack. A push operation thus involves copying data into the empty slot of the stack, then ad usting the stack pointer to point to the next free slot. Module Push stack[stack_pointer] = data stack_pointer = stack_pointer + 1 Module !nd !ets push the value "# onto the stack. $%ote& The stack could hold any data type, not necessarily decimal numbers. 'e have used numbers for simplicity(. The stack now looks like +--------+ | "# | +--------+ | | <------- Stack Pointer +--------+ | | +--------+ | | +--------+

Page 5 of 12

%ote how the stack pointer has been ad usted to point to the next free location in the stack. $%ote& for the time being we are ignoring certain problems. 'e will address these shortly)))(. Removing items from the stack To remove an item, first decrement (subtract * from) the stack pointer, then extract the data from that position in the stack. Module $e%o&e stack_pointer = stack_pointer - 1 data = stack[stack_pointer] Module !nd Time now to address the problems of the above implementation There are a number of problems associated with the above routines for pushing and removing items.

the push module does not check to see if the stack is full the remove module does not check to see if the stack is empty

There are a number of solutions to this problem. 'e shall present a simplified solution. 'e do not argue that it is the best, ust that it is one of a possible number of solutions. 'o%%ent( )ssu%e that the arra* ele%ents +egin at 1 'o%%ent( )ssu%e that the %a,i%u% ele%ents of the stack is M).ar( stack[M)-] ( /nteger Module /nitiali0e stack_pointer = 1 Module !nd Module Push if stack_pointer 1= M)- then return error else +egin stack[stack_pointer] = data stack_pointer = stack_pointer + 1 end Module !nd Module $e%o&e if stack_pointer <= 1 then return error else +egin stack_pointer = stack_pointer - 1 data = stack[stack_pointer] end Module !nd

Page 6 of 12

!"!"S +verybody has experience with ,ueues as they are common place. -ueues occur in cafeterias, petrol stations, shopping centres, anyplace where many people (customers) line up for few resources (cashier.s, salespeople, petrol pumps etc). The purpose of a ,ueue is to provide some form of buffering. Typical uses of ,ueues in computer systems are,

process management buffer between the fast computer and a slow printer

A ,ueue is defined as a data structure which holds a series of items to be processed on a first in first out basis (though some ,ueues can be sorted in priority). The operations associated with a ,ueue are,

initiali/e the ,ueue insert an item in the ,ueue remove an item from the ,ueue count the number of empty slots in the ,ueue count the number of items in the ,ueue

The following diagram shows an empty ,ueue. It is identified as a series of ten locations, and two pointers named front and rear. These two pointers keep track of where the front and rear of the ,ueue is. 1 2 3 " # 4 5 6 7 18 +---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | +---+---+---+---+---+---+---+---+---+---+ +---+ | 1 | 9ront +---+ +---+ | 18| $ear +---+ The front pointer is used to delete items, and the rear pointer insert items. Inserting two items called A and 0 will rearrange the ,ueue to look like, 1 2 3 " # 4 5 6 7 18 +---+---+---+---+---+---+---+---+---+---+ |)|:| | | | | | | | | +---+---+---+---+---+---+---+---+---+---+ +---+ | 1 | 9ront +---+ +---+ | 2 | $ear +---+ The pseudo1code for the various ,ueue operations follows.

Page 7 of 12

%odule initiali0e count = 8 head = 1 rear = si0e of ;ueue end %odule initiali0e %odule insert if count = si0e of ;ueue ;ueue is full and do not insert else +egin incre%ent count incre%ent rear if rear 1 si0e of ;ueue rear = 1 endif insert data at ;ueue[rear] endif end %odule insert %odule re%o&e if count = 8 ;ueue is e%pt* and do not re%o&e else +egin data = ;ueue[front] decre%ent count incre%ent front if front 1 si0e of ;ueue front = 1 endif endif end %odule re%o&e %odule count return count end %odule count %odule free_space return ;ueue.si0e - count end %odule free_space

The implementation of this is left to the student as a programming exercise.

Page 8 of 12

#$%K"& #$STS 2ata structures can be arranged in memory in a variety of different ways. +ach method has advantages and disadvantages. Arrays for example seem easy to use, where each element is stored se,uentially in memory. This type of approach is not efficient in larger computer systems, where a number of users share main memory. In such circumstances, there may not be enough contiguous main memory left to hold a se,uentially stored data structure like an array (but there could be enough if all the small free blocks were moved into one large block). 3ne way to overcome this is to link all elements of data together. 2ata is arranged into records, and a special item is added to each record called a pointer (a link field), which contains a link to the next record etc. 4enaming each record as a node and we have a complex data structure called a linked list. A linked list is a series of nodes connected together via pointers. 5ictorially, it looks like, <ode 1 +---+ <ode 2 +--------+--+ | +--------+--+ | | ------+ | | ------+ | +--------+--+ +--------+--+ =ata >ink =ata >nk In 5ascal, a node definition looks like, t*pe ptr = ?node node = record data ( string[28] ne,t ( ptr end +---+ <ode n | +--------+--+ | | +--------+--+ =ata >nk

Page 9 of 12

The following 5ascal program declares three nodes, inserts data into each of them, then using a pointer, cycles through the chain from node to node printing out the contents of each node. The value 6 is always stored in the last node of a chain, to indicate the end of the list. progra% linked_list t*pe ptr = ?node node = record data ( string[28] ne,t ( ptr end &ar node1@ node2@ node3 ( node nodeptr ( ptr +egin node1.data (= ABelco%e A node1.ne,t (= Cnode2 node2.data (= Ato A node2.ne,t (= Cnode3 node3.data (= A>inked >ists.A node3.ne,t (= nil nodeptr (= Cnode1 Dhile nodeptr <1 nil do +egin DriteE nodeptr?.data F nodeptr (= nodeptr?.ne,t end Driteln end. !inked lists are used in a wide variety of applications.

directory structures operating systems for process management data management in data base systems.

An advantage of storing data using a linked list is that the key se,uence can be altered by changing the pointers, not by moving data nodes. This means sorting data is ,uick, but searching is slower as you must follow the chain from node to node.

'AS'$%( 7ashing is a techni,ue used to improve data access times. 4ather than sorting the data according to a key, it computes the location of the data from the key. In simple terms, it computes an inde) value from the ke* of the desired record. At that index value, the record is stored8retrieved. If we had an array of *666 elements, we would expect our hash function (the method used to calculate the index value) to evenly distribute the keys over this range. In practice this is difficult to achieve. It is possible that two different search keys might generate the same hash value (ie, index), and we call this a collision. The si/e of the table (array) is generally a prime number, as this has the least probability of creating collisions.

Page 10 of 12

The following code segment defines an array of records in 5ascal which will be used to demonstrate hashing. const t*pe si0e = #11 data = record na%e ( string[28] age ( integer end hashta+le = arra*[1..si0e] of data

%ext, lets initiali/e the table with /ero.s, so this makes it easy to see if information is already stored at a particular element (important when inserting data later). procedure initiali0e E &ar Ga+le ( hashta+le F &ar i ( integer +egin for i (= 1 to si0e do +egin Ga+le[i].na%e (= A Ga+le[i].age (= 8 end end

The procedure insert will take the hash value and the data and insert it into the table. If the position is already occupied (ie, a collision occurs) the table will be searched from that point onwards till an empty slot occurs. procedure insert E Position ( integer !le%ent ( data &ar Ga+le ( hashta+le F +egin Dhile Ga+le[Position].na%e[1] <1 A A do Position (= EPosition + 1F %od si0e Ga+le[Position] (= !le%ent end The procedure hash will generate a hash value from a given data record. In deciding this, it must generate a value between * and #**. 3bviously, we cannot use the age field of the record, this will generate too many collisions. The best method is to add up the value of all the characters in the persons name, then extract nine bits from it (9:; < #*9) to generate the index value. procedure hash E &ar Position ( integer !le%ent ( data &ar Ga+le ( hashta+le F &ar i ( integer +egin i (= 1 position (= 8 Dhile i < 28 do position (= position + ordE!le%ent.na%e[i]F

Page 11 of 12

position (= position %od #11 end The remaining procedures to search and delete are left as a programming exercise for the student.

$%&"+"& S" !"%T$A# This method seeks to make a direct access file appear like a se,uence file. The se,uencing is achieved via an index table, which holds the keys of the records and their position within the file. A program reads the index se,uentially, and when it locates the key it desires, it reads the record from the indicated position. The advantages of this method are,

the records need not be in key se,uence the records may be processed se,uentially or directly

,$#" -"R($%( This is the process of merging two or more input files into a single output file (which are normally all se,uential in nature). The files to be merged are first sorted using the same key se,uence, which is preserved in the output file. A pseudo1code example for a 91way merge is shown below. progra% tDo_Da* %erge +egin read 1st record of infile1@ na%e as rec1 read 1st record of infile2@ na%e as rec2 Dhile rec1 or rec2 is not an end-of-record +egin if rec1.ke* < rec2.ke* +egin Drite rec1 to outfile read neD rec1 fro% infile1 end else +egin Drite rec2 to outfile read neD rec2 fro% infile2 end endif endDhile Drite end-of-record to outfile end progra% tDo_Da* %erge

Page 12 of 12
In case of a dynamic array type, the initial length of the array is zero. The actual length of the array must be set with the standard SetLengthfunction, which will allocate the necessary memory for storing the array elements.

Declaring Dynamic Arrays


For declaring dynamic arrays you do not mention the array range. For example: t"p$ 4arra" & arra" o* int$2$r; Aar a6 4arra"; Before using the array, you must declare the size using the setlengthfunction: s$tl$n2t+(a,/((); Now the array a have a valid array index range from 0 to 999: the array index is always zero-based. The following example declares and uses a two dimensional dynamic array: pro2ra, $!7"narra"; Aar a6 arra" o* arra" o* int$2$r; (* a F 4i,$nsional arra" *) i, 5 6 int$2$r; @$2in s$tl$n2t+(a,','); *or i6&( to G 4o *or 56&( to G 4o a.i,506& i * 5; *or i6&( to G 4o @$2in *or 56& ( to G 4o ?rit$(a.i,506F,B B); ?rit$ln; $n4; $n4. When the above code is compiled and executed, it produces following result: ( ( ( ( ( ( / F H G ( F G I J ( H I K /F ( G J /F /I

Potrebbero piacerti anche