Chapter 1
Introduction to DOS

Chapter 2
Introduction to Turbo Pascal

Chapter 3
Parts of a Pascal Program

Chapter 4
Control Structures and Looping

Chapter 5
Looping

Chapter 6
Procedures

Chapter 7
Parameters Passing

Chapter 8
Functions

Chapter 9
Arrays

Chapter 10
Searching and Sorting

Chapter 11
Records and File of Records

CHAPTER 10

( Searching and Sorting )   


It would be very convenient to have a long list of names and telephone numbers to be alphabetized. If you have such a list, you should be able to search through the names to find a telephone number. If the names were not alphabetized, it will take a long to find a telephone number of a friend! In this chapter we will learn how to perform sort and search on a list.

SEARCHING

If you wanted to print something stored in an array, you need to know the index of the element you are interested in. What happens if you forget the index? Is there any way to find the index? Yes, you can look through the list for the element, when you find a match you found the index. Suppose you have a parallel array of names and telephone numbers of seven of your friends.

1. JOHN 631-4431

2. PHILIP 834-3312

3. MARY 351-5522

4. KAY 531-6234

5. SAM 531-0064

6. JOE 563-3512

7. JACK 512-0695

You can print out the telephone number of the third person as follows:

writeln('Telephone number of ',name[3],' is: ',tele[3]);

Suppose you want to find the telephone number of JOE, but you do not know the index number. To find the telephone number, you will need to search through the array of names looking for JOE. If you find a match you have found the index number.

index := 0;

for count := 1 to 7 do

if name[count] = 'JOE' then index : = count;

Now to print the name and telephone number:

if index >0 then

writeln('Telephone number of ',name[index],' is: ',tele[index]);

Program 10-1 first sets up an array of 7 names and 7 corresponding telephone numbers. This is done through constant declaration of the array elements. There are many ways to do this. Ideally, you would read the names and telephone numbers from a file which is updated as needed. However, for the purpose of the search and sort examples, this method of array declaration is sufficient. In order to find the telephone number of a person the following steps needs need to be followed:

1 ) ask for the name of the person.
2 ) initialize index to 0.
3 ) search through the list for a match.
4 ) If match found set index to that element.
5 ) If the index is greater than 0 print the name, telephone number.
6 ) If the index remains zero then print 'Person not in file!'.


PROGRAM 10-1

Program ShowTele(input,output);

type

    ArrayType = array[1..7] of string[8];

    const

    Name : ArrayType = ('JOHN','PHILIP','MARY','KAY',

    'SAM','JOE','JACK');

    TELE : ArrayType= ('631-4431','834-3312','351-5522','531-6234',

    '531-0064','563-3512','512-0695');

    var

    person: string[8];

    index, i : integer;

begin

{ask name of the person}

    write ('Telephone number for who: ');readln(person);

    index := 0;

    for i := 1 to 7 do

    if person = name[i] then index : = i;

    {search through the list for the person

    if found write the telephone number}

    if index >0 then

      writeln('Telephone number of ',person, ' is: ',tele[index])

        else
          writeln('person not in file');

      end.

Program run:

Turbo Pascal Version 6.0 Copyright (c) 1983,90 Borland International

Telephone number for who: MARY

Telephone number of MARY is: 351-5522

Type EXIT to return to Turbo Pascal...

This program works quite well for such a small list. Suppose you had 1,000 names in the list. With this program you will have to wait until the entire 1,000 names have been searched, even though you may have found a match within the first 10 names. If different individuals had the same name, you will only get the telephone number of the last person with the match. Let us modify the program so that the first problem can be solved. To solve the second program we need the program to print each name with a match; in order to keep the program short, this is not discussed here.

PROGRAM 10-2

Program ShowTele(input,output);

type

    ArrayType = array[1..7] of string[8];

    const

    Name : ArrayType = ('JOHN','PHILIP','MARY','KAY',

    'SAM','JOE','JACK');

    TELE : ArrayType= ('631-4431','834-3312','351-5522','531-6234',

    '531-0064','563-3512','512-0695');

    var

    person: string[8];

    index, i : integer;

    found : boolean;

begin

    {ask name of the person}

    write ('Telephone number for who: ');readln(person);

    found := false;

    i:=1;

    while not(found) and (i <= 7) do

      BEGIN

      if person = name[i] then

      begin

        index := i;< /FONT> < /FONT>

        found := true;

      end;

      i:= i+1;

    END;

    {search through the list for the person

    if found write the telephone number}

    if found then

      writeln('Telephone number of ',person, ' is: ',tele[index])

    else
      writeln('person not in file');

end.

Program run:

Telephone number for who: JOHN

Telephone number of JOHN is: 631-4431

Type EXIT to return to Turbo Pascal...

Microsoft(R) MS-DOS(R) Version 5.00

(C)Copyright Microsoft Corp 1981-1991.

B:\>

In this example, since the names were not alphabetized, we had to search through the entire list. This type of searching is known as the sequential search through an unordered list or linear search. However, if the list was alphabetized, like a telephone directory, we could stop looking after a certain name is passed. For example, you were looking for Annet Brooks; you looked through all names beginning with 'Broo' and now you are at Jerry Brown. You know that either you passed the name you are looking for or the name is not listed.

If you have an alphabetized list you could look at the name in the middle of that list and determine whether the name you are interested in should be in the first half or the second half of the list. If it is in the first half of the list, you could look at the middle name of the first half of the list and determine whether the name is in the first half or the second half of that portion, and so on. This way, you cut the size of the list to one half each time. Such a searching technique is known as the binary search. We will not be covering the binary search here.

SORTING

A list of ten random numbers could be sorted from the smallest to the largest several different ways. One approach might be to look through the list find the smallest number, place it a second list called the sorted list and scratch it from the original list. Now look for the smallest number in the remaining list, place it in the sorted list and scratch it from the original list. Continue this until only one number is left in the original list, move it to the sorted list, and you are done. This algorithm can be used to sort a list in Pascal.

PROGRAM 10-3

end.

Program run:

Unsorted list:

15 11 33 51 3 2 12 36 98 53

The sorted list is:

2 3 11 12 15 33 36 51 53 98

Type EXIT to return to Turbo Pascal...

Microsoft(R) MS-DOS(R) Version 5.00

(C)Copyright Microsoft Corp 1981-1991.

B:\>

Since we can't scratch out a number from the memory, once a number is used, we would set it to a large number so it would be used as the smallest number again. Program 10-3 does the following:

1. places ten integers in an array of numbers.

2. prints these ten unsorted integers.

3. find the smallest number from the list 10 times.

4. when the smallest number is found save it's index.

5. move the smallest number to the sorted list.

6. scratch that number out from the original list.

(do this by making it a large number).

7. Print the sorted list.

The main disadvantage to this sort algorithm is that we have to have two arrays to do the sorting, the original array and the sorted one. The second disadvantage is that searching for the smallest should be done as many times as the total number of numbers. Each search goes through the whole list.

Another algorithm for sorting is known as the bubble sort. Bubble sort compares two adjacent numbers; if they are out of order, the numbers are swapped. Keep doing this until there are no more swaps. We will see that after one iteration of this bubbling process, the largest number would be at the bottom. Knowing this, the next time we only have to go through the list one less time. Let us modify the above program to the bubble sort.

 

PROGRAM 10-4

end. 

Program run:

Unsorted list:

15 11 33 51 3 2 12 36 98 53

The sorted list is:

15 11 33 51 3 2 12 36 98 53

Type EXIT to return to Turbo Pascal...

Microsoft(R) MS-DOS(R) Version 5.00

(C)Copyright Microsoft Corp 1981-1991.

B:\>

Notice that in Program 10-4 we compared the first number to the second number and so on:

If numbers[count] > numbers[count+1] then ...

We need to be very careful that count+1 does not go over the total number of elements we have in the list. In order to do this we make sure that 'count' will never get larger than one less than the total number of elements.

pass := pass -1 ;

for count := 1 to pass do ..;

If the list was sorted to begin with, the program will go through the repeat loop only one time. Since no swap occurred 'exchanged' will remain false, which will terminate the loop.

How can the bubble sort be applied to the name and telephone number list we discussed earlier in this chapter? Let us write a program to sort that list. However, here we have an unique problem, we only want to sort the names, not the telephone numbers. We want the telephone numbers to go with the names! Pay close attention to Program 10-5 to see how it is done.

PROGRAM 10-5

Program Sort3(input,output);

type

    ArrayType = array[1..7] of string[8];

    const

    Name : ArrayType = ('JOHN','PHILIP','MARY','KAY', 'SAM','JOE','JACK');< /FONT >

    TELE : ArrayType= ('631-4431','834-3312','351-5522','531-6234',

    '531-0064','563-3512','512-0695');

    var

    person, phone: string[8];

    index, i : integer;

    swapped : boolean;

begin

{write the unsorted lists}

writeln('Unsorted list: ');writeln;

for index := 1 to 7 do

    writeln(name[index],tele[index]:12);

    {sort the names and telephone numbers}

    i := 7;

    repeat

    i:=i -1;

    swapped := false;< /FONT>

    for index := 1 to i do< /P>

      if name[index] > name[index+1] then

      begin

        person := name[index];< /FONT>

        name[index] := name[index+1];< /FONT>

        name[index+1] := person;< /FONT>

        phone := tele[index];< /FONT>

        tele[index] := tele[index+1];< /FONT>

        tele[index+1]:= phone;

        swapped := true;< /FONT>

      end;

      until not(swapped);

      {print sorted names and telephone numbers}

      writeln('Sorted list: ');writeln;

      for index := 1 to 7 do

        < /FONT>

        writeln(name[index], tele[index]:12);

end.< /FONT>

 

Program run:

Unsorted list:

JOHN 631-4431

PHILIP 834-3312

MARY 351-5522

KAY 531-6234

SAM 531-0064

JOE 563-3512

JACK 512-0695

Sorted list:

JACK 512-0695

JOE 563-3512

JOHN 631-4431

KAY 531-6234

MARY 351-5522

PHILIP 834-3312

SAM 531-0064

Type EXIT to return to Turbo Pascal...

Microsoft(R) MS-DOS(R) Version 5.00

(C)Copyright Microsoft Corp 1981-1991.

B:\>

There are other sort algorithms that are used by Pascal programmers. One such sort algorithm is the Quick Sort. Quick Sort will not be discussed here. Another sort algorithm that you should be familiar with is the Merge Sort. If you have a list already sorted, but wanted to add just few names to it, there is no need to sort the whole list. You can do a merge sort. The small list should be sorted first. Then two pointers are used to go through the main list and the small list. Values from the two lists are compared, the smaller of the two is taken and written to the merged list. This process continues until the smaller list is exhausted. These algorithms are mentioned here for you to become familiar with the terms. These algorithms work well with recursion, which we have not discussed.


Go to top of this chapter

Site design/development provided by the UTPA NewMedia Center
@1999 The University of Texas-Pan American