9.Chapter9 Functions 精简 Skylar
9.Chapter9 Functions 精简 Skylar
Chapter 9 : Functions
Yupei Zhang
2018.10
Outlines
• 9.1 Defining and Calling Functions
• 9.2 Function Declarations
• 9.3 Arguments
• 9.4 The return Statement
• 9.5 Program Termination
• 9.6 Recursion
2
Introduction
• A function is a series of statements that have been
grouped together and given a name.
• Each function is essentially a small program, with its
own declarations and statements.
• Advantages of functions:
– A program can be divided into small pieces that are
easier to understand and modify.
– We can avoid duplicating code that’s used more than
once.
– A function that was originally part of one program can
be reused in other programs.
3
Why do we need functions?
4
9.1 Defining and Calling Functions
5
9.1 Defining and Calling Functions
• Program: Computing Averages
double average(double a, double b)
{
return (a + b) / 2;
}
– A function named average that computes the
average of two double values:
– The word double at the beginning is the return type
of average.
– The identifiers a and b (the function’s parameters)
represent the numbers that will be supplied when
average is called.
6
9.1 Defining and Calling Functions
• Program: Computing Averages
– Every function has an executable part, called the
body, which is enclosed in braces.
7
9.1 Defining and Calling Functions
• Program: Computing Averages
average(x, y) is a call of the average function.
– A function call consists of a function name followed by
a list of arguments.
– Arguments are used to supply information to a
function.
• The call average(x, y) causes the values of x and y
to be copied into the parameters a and b.
– An argument doesn’t have to be a variable; any
expression of a compatible type will do.
• average(5.1, 8.9) and average(x/2, y/3)
are legal.
8
9.1 Defining and Calling Functions
• Program: Computing Averages
– We’ll put the call of average in the place where we
need to use the return value.
– A statement that prints the average of x and y:
printf("Average: %g\n", average(x,
y));
The return value of average isn’t saved; the
program prints it and then discards it.
– If we had needed the return value later in the
program, we could have captured it in a variable:
avg = average(x, y);
9
9.1 Defining and Calling Functions
• Program: Computing Averages
– The average.c program reads three numbers and
uses the average function to compute their
averages, one pair at a time:
10
average.c
/* Computes pairwise averages of three numbers */
#include <stdio.h>
double average(double a, double b)
{
return (a + b) / 2;
}
int main(void)
{
double x, y, z;
printf("Enter three numbers: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y, average(x,
y));
printf("Average of %g and %g: %g\n", y, z, average(y,
z));
printf("Average of %g and %g: %g\n", x, z, average(x,
z));
Demo: average.c
return 0; 11
9.1 Defining and Calling Functions
• Program: Printing a Countdown
void print_count(int n)
{
printf("T minus %d and counting\n",
n);
}
– To indicate that a function has no return value, we specify
that its return type is void. void is a type with no
values.
– A call of print_count must appear in a statement by
itself:
print_count(i);
– The countdown.c program calls print_count 10
times inside a loop.
12
countdown.c
/* Prints a countdown */
#include <stdio.h>
void print_count(int n)
{
printf("T minus %d and counting\n", n);
}
int main(void)
{
int i;
14
pun2.c
/* Prints a bad pun */
#include <stdio.h>
void print_pun(void)
{
printf("To C, or not to C: that is the question. \
n");
}
int main(void)
{
print_pun();
return 0; Demo: pun2.c
}
15
9.1 Defining and Calling Functions
• Function Definitions
– General form of a function definition:
16
9.1 Defining and Calling Functions
• Function Definitions
– Return Type
• The return type of a function is the type of value
that the function returns.
• Rules governing the return type:
– Functions may not return arrays.
– Specifying that the return type is void
indicates that the function doesn’t return a
value.
• If the return type is omitted in C89, the function
is presumed to return a value of type int.
• In C99, omitting the return type is illegal.
17
9.1 Defining and Calling Functions
• Function Definitions
– Function parameters
• After the function name comes a list of
parameters.
• Each parameter is preceded by a specification of
its type;
• parameters are separated by commas.
• If the function has no parameters, the word void
should appear between the parentheses.
19
9.1 Defining and Calling Functions
• Function Definitions
– Function Body
• The body of a function may include both
declarations and statements.
• An alternative version of the average function:
sum = a + b; /* statement */
return sum / 2; /* statement */
}
20
9.1 Defining and Calling Functions
• Function Definitions
– Function Body
• Variables declared in the body of a function can’t
be examined or modified by other functions.
• In C89, variable declarations must come first,
before all statements in the body of a function.
• In C99, variable declarations and statements can be
mixed, as long as each variable is declared prior to
the first statement that uses the variable.
21
9.1 Defining and Calling Functions
• Function Calls
– A function call consists of a function name followed
by a list of arguments, enclosed in parentheses:
average(x, y)
print_count(i)
print_pun()
– If the parentheses are missing, the function won’t be
called:
print_pun; /*** WRONG ***/
This statement is legal but has no effect.
23
9.1 Defining and Calling Functions
• Function Calls
– A call of a void function is always followed by a semicolon
to turn it into a statement:
print_count(i);
print_pun();
– A call of a non-void function produces a value that can be
stored in a variable, tested, printed, or used in some other
way:
avg = average(x, y);
if (average(x, y) > 0)
printf("Average is positive\n");
25
9.1 Defining and Calling Functions
• Function Calls
– Ignoring the return value of average is an odd thing
to do, but for some functions it makes sense.
– printf returns the number of characters that it
prints.
– After the following call, num_chars will have the
value 9:
num_chars = printf("Hi, Mom!\n");
– We’ll normally discard printf’s return value:
printf("Hi, Mom!\n");
/* discards return value */
26
9.1 Defining and Calling Functions
• Program: Testing Whether a Number Is Prime
– The prime.c program tests whether a number is
prime. Uses a function named is_prime that
returns true if its parameter is a prime number and
false if it isn’t.
Enter a number: 34
Not prime
28
prime.c
/* Tests whether a number is prime */
bool is_prime(int n)
{
int divisor;
if (n <= 1)
return false;
for (divisor = 2; divisor * divisor <= n; divisor+
+)
if (n % divisor == 0)
return false;
return true;
}
29
int main(void)
{
int n;
Demo: prime.c
30
9.2 Function Declarations
• C doesn’t require that the definition of a function
precede its calls.
• Suppose that we rearrange the average.c
program by putting the definition of average after
the definition of main.
31
9.2 Function Declarations
#include <stdio.h>
int main(void)
{
double x, y, z;
printf("Enter three numbers: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y,
average(x,y));
printf("Average of %g and %g: %g\n", y, z,
average(y,z));
printf("Average of %g and %g: %g\n", x, z,
average(x,z));
return 0;
}
double average(double a, double b)
{ Demo: fnDeclare.c
return (a + b) / 2;
} 32
9.2 Function Declarations
• When the compiler encounters the first call of
average in main, it has no information about the
function.
• Instead of producing an error message, the compiler
assumes that average returns an int value.
• We say that the compiler has created an implicit
declaration of the function.
33
9.2 Function Declarations
• The compiler is unable to check that we’re passing
average the right number of arguments and that the
arguments have the proper type.
• Instead, it performs the default argument promotions
and hopes for the best.
• When it encounters the definition of average later in
the program, the compiler notices that the function’s
return type is actually double, not int, and so we
get an error message.
34
9.2 Function Declarations
• One way to avoid the problem of call-before-
definition is to arrange the program so that the
definition of each function precedes all its calls.
• Unfortunately, such an arrangement doesn’t always
exist.
• Even when it does, it may make the program harder
to understand by putting its function definitions in an
unnatural order.
35
9.2 Function Declarations
• Fortunately, C offers a better solution: declare each
function before calling it.
• A function declaration provides the compiler with a brief
glimpse at a function whose full definition will appear
later.
• General form of a function declaration:
return-type function-name ( parameters ) ;
• The declaration of a function must be consistent with the
function’s definition.
• Here’s the average.c program with a declaration of
average added.
36
9.2 Function Declarations
#include <stdio.h>
double average(double a, double b); /* DECLARATION */
int main(void)
{
double x, y, z;
printf("Enter three numbers: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y,
average(x,y));
printf("Average of %g and %g: %g\n", y, z,
average(y,z));
printf("Average of %g and %g: %g\n", x, z,
average(x,z));
return 0;
}
double average(double a, double b) /* DEFINITION */
{
return (a + b) / 2;
} 37
9.2 Function Declarations
• Function declarations of the kind we’re discussing are
known as function prototypes.
• C also has an older style of function declaration in
which the parentheses are left empty.
double average();
• A function prototype doesn’t have to specify the
names of the function’s parameters, as long as their
types are present:
double average(double, double);
• It’s usually best not to omit parameter names.
38
9.2 Function Declarations
• C99 has adopted the rule that either a declaration or
a definition of a function must be present prior to
any call of the function.
39
9.3 Arguments
• In C, arguments are passed by value:
– when a function is called, each argument is
evaluated and its value assigned to the
corresponding parameter.
– Since the parameter contains a copy of the
argument’s value, any changes made to the
parameter during the execution of the function
don’t affect the argument.
40
9.3 Arguments
• The fact that arguments are passed by value has both
advantages and disadvantages.
– Since a parameter can be modified without affecting the
corresponding argument, we can use parameters as variables
within the function, reducing the number of genuine variables
needed.
• Consider the following function, which raises a number x to a
power n:
int power(int x, int n)
{
int i, result = 1;
return result;
} 41
9.3 Arguments
• Since n is a copy of the original exponent, the function
can safely modify it, removing the need for i:
int power(int x, int n)
{
int result = 1;
return result;
}
42
9.3 Arguments
• C’s requirement that arguments be passed by value makes
it difficult to write certain kinds of functions.
• Suppose that we need a function that will decompose a
double value into an integer part and a fractional part.
• Since a function can’t return two numbers, we might try
passing a pair of variables to the function and having it
modify them:
void decompose(double x, long int_part,
double frac_part)
{
int_part = (long) x;
frac_part = x - int_part;
}
43
9.3 Arguments
• A call of the function:
decompose(3.14159, i, d);
• Unfortunately, i and d won’t be affected by the
assignments to int_part and frac_part.
• Chapter 11 shows how to make decompose work
correctly.
44
9.3 Arguments
• Argument Conversions
– C allows function calls in which the types of the
arguments don’t match the types of the parameters.
– The rules governing how the arguments are converted
depend on whether or not the compiler has seen a
prototype for the function (or the function’s full
definition) prior to the call.
45
9.3 Arguments
• Argument Conversions
– The compiler has encountered a prototype prior to
the call.
• The value of each argument is implicitly converted to
the type of the corresponding parameter as if by
assignment.
• Example:
• If an int argument is passed to a function that was
expecting a double, the argument is converted to
double automatically.
46
9.3 Arguments
• Argument Conversions
– The compiler has not encountered a prototype prior
to the call.
• The compiler performs the default argument
promotions:
– float arguments are converted to double.
– The integral promotions are performed, causing
char and short arguments to be converted to
int. (In C99, the integer promotions are
performed.)
47
9.3 Arguments
• Argument Conversions
– Relying on the default argument promotions is dangerous.
– Example:
#include <stdio.h>
int main(void)
{
double x = 3.0;
printf("Square: %d\n", square(x));
return 0;
}
int square(int n)
{
return n * n;
}
– At the time square is called, the compiler doesn’t know that it
expects an argument of type int.
48
9.3 Arguments
• Argument Conversions
– Instead, the compiler performs the default argument
promotions on x, with no effect.
– Since it’s expecting an argument of type int but has been
given a double value instead, the effect of calling square
is undefined.
– The problem can be fixed by casting square’s argument to
the proper type:
printf("Square: %d\n", square((int) x));
– A much better solution is to provide a prototype for
square before calling it.
– In C99, calling square without first providing a declaration
or definition of the function is an error.
49
9.3 Arguments
• Array Arguments
– When a function parameter is a one-dimensional
array, the length of the array can be left unspecified:
int f(int a[]) /* no length specified */
{
…
}
– C doesn’t provide any easy way for a function to
determine the length of an array passed to it.
– Instead, we’ll have to supply the length—if the
function needs it—as an additional argument.
50
9.3 Arguments
• Array Arguments
– Example:
int sum_array(int a[], int n)
{
int i, sum = 0;
51
9.3 Arguments
• Array Arguments
– The prototype for sum_array has the following
appearance:
int sum_array(int a[], int n);
– As usual, we can omit the parameter names if we
wish:
int sum_array(int [], int);
52
9.3 Arguments
• Array Arguments
– When sum_array is called, the first argument will be
the name of an array, and the second will be its length:
#define LEN 100
int main(void)
{
int b[LEN], total;
…
total = sum_array(b, LEN);
…
}
– Notice that we don’t put brackets after an array name
when passing it to a function.
total = sum_array(b[], LEN); /*** WRONG ***/
53
9.3 Arguments
• Array Arguments
– A function has no way to check that we’ve passed it
the correct array length.
– We can exploit this fact by telling the function that the
array is smaller than it really is.
– Suppose that we’ve only stored 50 numbers in the b
array, even though it can hold 100.
– We can sum just the first 50 elements by writing
total = sum_array(b, 50);
54
9.3 Arguments
• Array Arguments
– Be careful not to tell a function that an array argument
is larger than it really is:
total = sum_array(b, 150); /*** WRONG ***/
sum_array will go past the end of the array, causing
undefined behavior.
55
9.3 Arguments
• Array Arguments
– A function is allowed to change the elements of an
array parameter, and the change is reflected in the
corresponding argument.
– A function that modifies an array by storing zero into
each of its elements:
void store_zeros(int a[], int n)
{
int i;
56
9.3 Arguments
• Array Arguments
– A call of store_zeros:
store_zeros(b, 100);
– The ability to modify the elements of an array
argument may seem to contradict the fact that C
passes arguments by value.
– Chapter 12 explains why there’s actually no
contradiction.
57
9.3 Arguments
• Array Arguments
– If a parameter is a multidimensional array, only the length
of the first dimension may be omitted.
– If we revise sum_array so that a is a two-dimensional
array, we must specify the number of columns in a:
#define LEN 10
int sum_two_dimensional_array(int a[][LEN], int
n)
{
int i, j, sum = 0;
for (i = 0; i < n; i++)
for (j = 0; j < LEN; j++)
sum += a[i][j];
return sum;
}
58
9.3 Arguments
• Array Arguments
– Not being able to pass multidimensional arrays with
an arbitrary number of columns can be a nuisance.
– We can often work around this difficulty by using
arrays of pointers.
– C99’s variable-length array parameters provide an
even better solution.
59
9.4 The return Statement
• A non-void function must use the return
statement to specify what value it will return.
• The return statement has the form
return expression ;
• The expression is often just a constant or variable:
return 0;
return status;
• More complex expressions are possible:
return n >= 0 ? n : 0;
60
9.4 The return Statement
• If the type of the expression in a return statement
doesn’t match the function’s return type, the
expression will be implicitly converted to the return
type.
– If a function returns an int, but the return
statement contains a double expression, the value
of the expression is converted to int.
61
9.4 The return Statement
• return statements may appear in functions whose
return type is void, provided that no expression is
given:
return; /* return in a void function */
• Example:
void print_int(int i)
{
if (i < 0)
return;
printf("%d", i);
}
62
9.4 The return Statement
• A return statement may appear at the end of a void
function:
void print_pun(void)
{
printf("To C, or not to C: that is the
question.\n");
return; /* OK, but not needed */
}
Using return here is unnecessary.
• If a non-void function fails to execute a return
statement, the behavior of the program is undefined if it
attempts to use the function’s return value.
63
9.5 Program Termination
• Normally, the return type of main is int:
int main(void)
{
…
}
• Older C programs often omit main’s return type,
taking advantage of the fact that it traditionally
defaults to int:
main()
{
…
}
64
9.5 Program Termination
• Omitting the return type of a function isn’t legal in
C99, so it’s best to avoid this practice.
• Omitting the word void in main’s parameter list
remains legal, but—as a matter of style—it’s best to
include it.
65
9.5 Program Termination
• The value returned by main is a status code that can
be tested when the program terminates.
• main should return 0 if the program terminates
normally.
• To indicate abnormal termination, main should
return a value other than 0.
• It’s good practice to make sure that every C program
returns a status code.
66
9.5 Program Termination
• The exit Function
– Executing a return statement in main is one way to
terminate a program.
– Another is calling the exit function, which belongs
to <stdlib.h>.
– The argument passed to exit has the same meaning
as main’s return value: both indicate the program’s
status at termination.
– To indicate normal termination, we’d pass 0:
exit(0); /* normal termination */
67
9.5 Program Termination
• The exit Function
– Since 0 is a bit cryptic, C allows us to pass
EXIT_SUCCESS instead (the effect is the same):
exit(EXIT_SUCCESS);
– Passing EXIT_FAILURE indicates abnormal
termination:
exit(EXIT_FAILURE);
– EXIT_SUCCESS and EXIT_FAILURE are macros
defined in <stdlib.h>.
– The values of EXIT_SUCCESS and EXIT_FAILURE
are implementation-defined; typical values are 0 and
1, respectively.
68
9.5 Program Termination
• The exit Function
– The statement
return expression;
in main is equivalent to
exit(expression);
– The difference between return and exit is that
exit causes program termination regardless of
which function calls it.
– The return statement causes program termination
only when it appears in the main function.
69
9.6 Recursion
• A function is recursive if it calls itself.
• The following function computes n! recursively, using
the formula n! = n × (n – 1)!:
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
70
9.6 Recursion
• To see how recursion works, let’s trace the execution
of the statement
i = fact(3);
71
9.6 Recursion
• The following recursive function computes xn, using
the formula xn = x × xn–1.
int power(int x, int n)
{
if (n == 0)
return 1;
else
return x * power(x, n - 1);
}
72
9.6 Recursion
• We can condense the power function by putting a
conditional expression in the return statement:
int power(int x, int n)
{
return n == 0 ? 1 : x * power(x, n - 1);
}
• Both fact and power are careful to test a
“termination condition” as soon as they’re called.
• All recursive functions need some kind of
termination condition in order to prevent infinite
recursion.
73
9.6 Recursion
• Recursion
– Recursion is most helpful for sophisticated
algorithms that require a function to call itself two
or more times.
– Recursion often arises as a result of an algorithm
design technique known as divide-and-conquer, in
which a large problem is divided into smaller pieces
that are then tackled by the same algorithm.
74
9.6 Recursion
• The Quicksort Algorithm
– A classic example of divide-and-conquer can be found
in the popular Quicksort algorithm.
– Assume that the array to be sorted is indexed from 1
to n.
Quicksort algorithm
1. Choose an array element e (the “partitioning element”), then
rearrange the array so that elements 1, …, i – 1 are less than
or equal to e, element i contains e, and elements i + 1, …, n
are greater than or equal to e.
2. Sort elements 1, …, i – 1 by using Quicksort recursively.
3. Sort elements i + 1, …, n by using Quicksort recursively.
75
9.6 Recursion
• The Quicksort Algorithm
– A classic example of divide-and-conquer can be found
in the popular Quicksort algorithm.
– Assume that the array to be sorted is indexed from 1
to n.
Quicksort algorithm
1. Choose an array element e (the “partitioning element”), then
rearrange the array so that elements 1, …, i – 1 are less than
or equal to e, element i contains e, and elements i + 1, …, n
are greater than or equal to e.
2. Sort elements 1, …, i – 1 by using Quicksort recursively.
3. Sort elements i + 1, …, n by using Quicksort recursively.
76
9.6 Recursion
• The Quicksort Algorithm
– Step 1 of the Quicksort algorithm is obviously critical.
– There are various methods to partition an array.
– We’ll use a technique that’s easy to understand but
not particularly efficient.
– The algorithm relies on two “markers” named low
and high, which keep track of positions within the
array.
77
9.6 Recursion
• The Quicksort Algorithm
– Initially, low points to the first element; high points to the last.
– We copy the first element (the partitioning element) into a
temporary location, leaving a “hole” in the array.
– Next, we move high across the array from right to left until it
points to an element that’s smaller than the partitioning
element.
– We then copy the element into the hole that low points to,
which creates a new hole (pointed to by high).
– We now move low from left to right, looking for an element
that’s larger than the partitioning element. When we find
one, we copy it into the hole that high points to.
– The process repeats until low and high meet at a hole.
– Finally, we copy the partitioning element into the hole.
78
9.6 Recursion
• The Quicksort Algorithm
– Example of partitioning an array:
79
9.6 Recursion
• The Quicksort Algorithm
– By the final figure, all elements to the left of the
partitioning element are less than or equal to 12, and
all elements to the right are greater than or equal to
12.
– Now that the array has been partitioned, we can use
Quicksort recursively to sort the first four elements of
the array (10, 3, 6, and 7) and the last two (15 and 18).
80
9.6 Recursion
• Program: Quicksort
– Let’s develop a recursive function named quicksort
that uses the Quicksort algorithm to sort an array of
integers.
– The qsort.c program reads 10 numbers into an array,
calls quicksort to sort the array, then prints the
elements in the array:
Enter 10 numbers to be sorted: 9 16 47 82 4
66 12 3 25 51
In sorted order: 3 4 9 12 16 25 47 51 66 82
– The code for partitioning the array is in a separate
function named split.
81
qsort.c
/* Sorts an array of integers using Quicksort algorithm */
#include <stdio.h>
#define N 10
void quicksort(int a[], int low, int high);
int split(int a[], int low, int high);
int main(void)
{
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
quicksort(a, 0, N - 1);
printf("In sorted order: ");
for (i = 0; i < N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
82
void quicksort(int a[], int low, int high)
{
int middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
83
int split(int a[], int low, int high)
{
int part_element = a[low];
for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];
while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}
84
9.6 Recursion
• Program: Quicksort
– Ways to improve the program’s performance:
• Improve the partitioning algorithm.
• Use a different method to sort small arrays.
• Make Quicksort non recursive.
85
Exercises :
87
Selection Sort
1st Iteration
2nd Iteration
3rd Iteration
4th Iteration
5th Iteration
6th Iteration
88
Selection Sort
89
Selection Sort
90
• Program
• Input: input a integer N, then generate N
random integers that lie in [0,99].
• Output: print the N integers in ascending
order
91
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4 void SelectionSort(int A[],int n)
5 {
6 int i,j,k,t;
7 for(i=0; i<n-1; i++) {
8 k=i;
9 for(j=i+1; j<n; j++)//an iteration
10 if (A[j]<A[k]) k=j;//>
11 if(i!=k)
12 t=A[i], A[i]=A[k], A[k]=t;
13 }
14 }
92
15 #define N 10
16 int main()
17 {
18 int A[N],i;
19 srand((unsigned int)time(0));
20 for(i=0; i<N; i++) {
21 A[i] = rand()%100;
22 printf("%d ",A[i]);
23 }
24 SelectionSort(A,N);
25 printf("\n");
26 for(i=0;i<N;i++) printf("%d ", A[i]);
27 return 0;
28 }
93
Bubble Sort
• Starting with the last list element, we compare successive
pairs of elements, swapping whenever the bottom
element of the pair is smaller than the one above it
• In this way the smallest element “bubbles up” to the top
of the list.
• Each iteration puts the smallest unsorted item into its
correct place using the same technique, but it also makes
changes in the locations of the other elements in the array
94
Bubble Sort
95
Bubble sort
1st Iteration 6
2nd Iteration 5
3rd Iteration 4
4th Iteration 3
5th Iteration 2
6th Iteration 1
96
1 #include <stdio.h>
2
3 #define N 10 //array length
4 int main()
5 {
6 int A[N], i, j, t;
7 for (i=0; i<N; i++)
8 scanf("%d",&A[i]);
9 for(j=0 ; j<N-1 ; j++)
10 for(i=0 ; i<N-1-j; i++)
11 if(A[i] > A[i+1])
12 t=A[i],A[i]=A[i+1],A[i+1]=t;
13 for (i=0; i<N; i++)
14 printf("%d ",A[i]);
15 return 0;
16 }
97
Insertion Sort
• Insertion sort iterates, consuming one input element
each repetition, and growing a sorted output list.
• Each iteration, insertion sort removes one element
from the input data, finds the location it belongs
within the sorted list, and inserts it there. It repeats
until no input elements remain.
98
Insert Sort
1st Iteration
2nd Iteration
3rd Iteration
4th Iteration
5th Iteration
6th Iteration
99
Insertion Sort
100
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4 void InsertionSort(int A[],int n)
5 {
6 int i,k,t;
7 for(i=1; i<n; i++) { //insert sort
8 t=A[i]; k=i-1;
9 while(t < A[k]) {// >
10 A[k+1] = A[k]; k--;
11 if(k==-1) break;
12 }
13 A[k+1]=t;
14 }
15 }
101
16 #define N 10
17 int main()
18 {
19 int A[N],i;
20 srand((unsigned int)time(0));
21 for(i=0; i<N; i++) {//random generate
22 A[i] = rand()%100;
23 printf("%d ",A[i]);
24 }
25 InsertionSort(A,N);
26 printf("\n");
27 for(i=0;i<N;i++) printf("%d ", A[i]);
28 return 0;
29 }
102
Linear Search
103
1 #include <stdio.h>
2 int Search(int A[],int n,int find)
3 {//n is array length, find is the item to be searched
4 int i;
5 for (i=0; i<n ; i++)
if (A[i]==find) return i;
6 return -1; //unfound
7 }
104
8 #define N 10
9 int main()
10 {
11 int A[N]={18,-3,-12,34,101,211,12,90,
77,45}, i,find;
12 scanf("%d",&find);
13 i=Search(A,N,find);
14 if(i>=0) printf("A[%d]=%d\n",i,find);
15 else printf("not found\n");
16 return 0;
17 }
105
Binary Search
• The Number Guessing Game
– Make a number in your mind between 1 and 100
– Let another student guess the number
– What is your strategy?
106
Binary Search
• The binary search algorithm assumes that the items
in the list being searched are sorted.
• The algorithm begins at the middle of the list.
• If the item which we are searching is less than the middle item,
continue searching the data in the first half of the list.
• If the item is greater than the middle item, continue searching
between the middle and the end of the list.
• If the middle item is equal to the one for which you are searching,
the search stops.
• The process continues with each comparison cutting in half the
portion of the list where the item might be.
• The process stops when the item is found or when the portion of
the list where the item might be is empty.
Binary Search
-1
108
1 #include <stdio.h>
2 int BinarySearch(int A[],int n,int find)
3 {
4 int low, high, mid;
5 low =0 , high=n-1;
6 while(low<=high) {
7 mid = low + (high-low)/2;
8 if( A[mid]<find) low=mid+1;
9 else if (A[mid]>find) high=mid-1;
10 else return mid; //found
11 }
12 return -1; //unfound
13 }
109
14 #define N 10
15 int main()
16 {
17 int A[N]={8,24,30,47,62,68,83,90,
92,95},i,find;
18 scanf("%d",&find);
19 i=BinarySearch(A,N,find);
20 if(i >= 0)
printf("A[%d]=%d\n",i,find);
21 else printf("not found\n");
22 return 0;
23 }
110
Exercises :
113
The End
114
About Theory Exam :
1. Written exam.
2. In 2 hours.
3. Single choice;
Correct programs;
Fill blanks in programs;
Read programs and answer questions;
4. Write programs.(choose 2 from 4)
The End
116