Вы находитесь на странице: 1из 23

Data Structures and Algorithms

Data type and Arrays


Instructor: Chien-Yu Chen BIME@NTU

Choice of proper data structure


once the choice has been made, the necessary algorithms are simple. For the same data, some data structures require more or less space than others; for the same operations on the data, some data structures lead to more or less efficient algorithms than others.
Chien-Yu Chen, BIME@NTU

Data structure
A data structure is not a passive object: We also must consider the operations to be performed on it (and the algorithms used for these operations). The data structures that we consider in this chapter are important building blocks that we can use in a natural manner in C++ and many other programming languages.

Chien-Yu Chen, BIME@NTU

type and function


Types allow us to specify how we will use particular sets of bits and functions allow us to specify the operations that we will perform on the data.

Chien-Yu Chen, BIME@NTU

Basic type of data


Integers (ints)
int, lont int, short int

Floating-point numbers (floats)


float, double

Characters (chars)

Chien-Yu Chen, BIME@NTU

Type-dependent operations

Chien-Yu Chen, BIME@NTU

Program 3-1

Chien-Yu Chen, BIME@NTU

Program 3-2

Chien-Yu Chen, BIME@NTU

Program 3-2 (cont.)

Chien-Yu Chen, BIME@NTU

Changing data type

Chien-Yu Chen, BIME@NTU

Using header file


In C++, an alternative approach is to put the typedef and randNum into a separate header filecalled, say, Number.hreplacing them with the directive include Number.h in the code in Program 3.2.

Chien-Yu Chen, BIME@NTU

interface

Chien-Yu Chen, BIME@NTU

An example in C
/* in the file named Number.h */ typedef int Number; Number randNum(); /* in the file named int.c */ #include <stdlib.h> #include Number.h Number randNum() { return rand(); } /* in the file named avg.c */ #include <stdlib.h> #include <math.h> #include Number.h ...

Chien-Yu Chen, BIME@NTU

Chien-Yu Chen, BIME@NTU

pointer
A pointer is a reference to an object in memory (usually implemented as a machine address). We declare a variable a to be a pointer to (for example) an integer by writing int *a, and we can refer to the integer itself as *a. We can declare pointers to any type of data. The unary operator & gives the machine address of an object, and is useful for initializing pointers. For example, *&a is the same as a.
Chien-Yu Chen, BIME@NTU

New data type


Implementation Using it

Chien-Yu Chen, BIME@NTU

Arrays

a[i]

Using pointers

Chien-Yu Chen, BIME@NTU

Sieve of Eratosthenes
Eratosthenes (276~194 BC) . Eratosthenes (Sieve). , 100
2~100 2, 2 , 2 3, 3 , 3 5, 5 , 5 ..., , , 2,3,5,7,...,97 100
http://home.educities.edu.tw/kuen/maths/algorithm01.htm
Chien-Yu Chen, BIME@NTU

Chien-Yu Chen, BIME@NTU

Dynamic memory allocation

Chien-Yu Chen, BIME@NTU

Chien-Yu Chen, BIME@NTU

Chien-Yu Chen, BIME@NTU

Вам также может понравиться