Sie sind auf Seite 1von 29

CS1010E Lecture 9

Problem Solving With


One Dimensional Arrays
Henry Chia
hchia@comp.nus.edu.sg

Semester 1 2011 / 2012


Department of Computer Science
School Of Computing
National University Of Singapore

CS1010E Lecture 9 p.1/29

Lecture Outline
Selection sort
Searching
Linear search
Binary search
Random number generation
Integer sequences
Floating-point sequences
Array of Structures

CS1010E Lecture 9 p.2/29

Sorting Algorithms
Sorting a group of data values is an operation
that is routinely used when analyzing massive
amounts of data.
Sorting is typically used as a pre-processing
step for the following tasks:
Counting occurrences of similar data.
Finding duplicate values.
Efficient search for a particular data.
We will present the selection sort algorithm.

CS1010E Lecture 9 p.3/29

Selection Sort
Find the minimum value and exchange it with
the value in the first position in the array.
Find the minimum value beginning with the
second element, and exchange with the
second element.
This process continues until reaching the
next-to-last element.
At this point, the entire array of values will be
in ascending order.

CS1010E Lecture 9 p.4/29

Selection Sort
Original order:
5 3 12 8 1

Exchange the minimum with the value in the


first position:
1 3 12 8 5 9
Exchange the minimum with the value in the
second position:
1 3 12 8 5 9
Exchange the minimum with the value in the
third position:
1 3 5 8 12 9
CS1010E Lecture 9 p.5/29

Selection Sort
Exchange the minimum with the value in the
fourth position:
1 3 5 8 12 9
Exchange the minimum with the value in the
fifth position:
1 3 5 8 9 12
Array values are now in ascending order!

CS1010E Lecture 9 p.6/29

Selection Sort
void selectionSort(int list[],int numElem)
{
int i, j, minIndex, temp;
for (i = 0; i < numElem-1; i++)
{
minIndex = i;
for (j = i+1; j < numElem; j++)
if (list[j] < list[minIndex])
minIndex = j;
if (minIndex != i) // to avoid redundant swaps
{
temp = list[minIndex];
list[minIndex] = list[i];
list[i] = temp;
}
}
return;
}
CS1010E Lecture 9 p.7/29

Selection Sort
In general, a selection sort technique requires
locating an extremum (maximum or minimum
value) and exchanging it with a value at an
extreme (rightmost or leftmost) end.
A selection sort algorithm can be written for
Ascending or descending arrangement.
Extremum as minimum or maximum value.
Finding the extremum in a left-to-right, or
right-to-left traversal of the array.

CS1010E Lecture 9 p.8/29

Search Algorithms
Another common operation performed with
arrays is searching for a specific value, e.g.
Finding first/last occurrence
Counting occurrences
Searching algorithms fall into two groups:
those for searching an unordered array and
those for searching an ordered array.
A search function either returns the position
of the desired value in the array or returns a
value of 1 if the desired value is not in the
array.
CS1010E Lecture 9 p.9/29

Linear Search
Consider searching an unordered list of
values.
int linearSearch(int list[], int numElem,
int value)
{
int i=0, index=-1;
while (i < numElem && list[i] != value)
i++;
if (i < numElem)
index = i;
return index;
}

CS1010E Lecture 9 p.10/29

Linear Search
Consider searching an ordered list of values.
Example: searching for the value 25 in:
-7 2 14 38 52 77 105
As soon as the value 38 is reached, conclude
that 25 is not in the list.
int linearSearch(int list[], int numElem, int value)
{
int i=0;
while (i < numElem && list[i] < value)
i++;
if (i < numElem && list[i] == value)
return i;
else
return -1;
}
CS1010E Lecture 9 p.11/29

Binary Search
More efficient algorithm for searching an
ordered list.
Check the middle of the array and
determine if the value is in the first half or
second half of the array.
Within the half array, check the middle and
determine if the value is in the first quarter
or the second quarter of the array.
The process of dividing the array into
smaller and smaller pieces continues until
the value is found or further division is no
longer possible.
CS1010E Lecture 9 p.12/29

Binary Search
Search for value 14 in the following list:
-7 2 14 38 52 77 105
l
m
r
38 > 14 so choose top half:
-7 2 14 38 52 77
l m
r
2 < 14:
-7 2

14
lr
m

38

52

77

105

105

14 = 14 so it is found!
CS1010E Lecture 9 p.13/29

Binary Search
Search for value 25 in the following list:
-7 2 14 38 52 77 105
l
m
r
38 > 25 so choose top half:
-7 2 14 38 52 77
l m
r
2 < 25:
-7 2

14
lr
m

38

52

77

105

105

CS1010E Lecture 9 p.14/29

Binary Search
14 < 25:
-7 2 14
r
m

38
l

52

77

105

l > r so item is not found!

CS1010E Lecture 9 p.15/29

Binary Search
int binarySearch(int list[], int numElem, int value)
{
int left=0, right=numElem-1, mid, index=-1;
while ((left <= right) && (index == -1))
{
mid = (left + right)/2;
if (list[mid] == value)
index = mid;
else
if (list[mid] > value)
right = mid - 1;
else
left = mid + 1;
}
return index;
}

CS1010E Lecture 9 p.16/29

Random Numbers
Many simulation applications often require
random numbers distributed between
specified values.
For example, we may want to generate
random integers between 1 and 500, or we
may want to generate random floating-point
values between 5 and 5.
The random numbers generated are equally
likely to occur; if the random number is
supposed to be an integer between 1 and 5,
each of the integers in the set {1, 2, 3, 4, 5} is
equally likely to occur.
CS1010E Lecture 9 p.17/29

Random Numbers
The Standard C library contains a function
rand that generates a random integer
between 0 and RAND_MAX, where RAND_MAX
is a system-dependent integer defined in
stdlib.h.
The rand function has no input arguments
and is referenced by the expression rand().

CS1010E Lecture 9 p.18/29

Random Numbers
int main(void)
{
int i, r, list[10];
for (i=0; i<10; i++)
list[i] = rand();

void printArray(int t[],


int numElem)
{
int i;

printArray(list,10);

for (i=0; i<numElem; i++)


printf("%d ", t[i]);
printf("\n");

return 0;

return;
}

What happens each time the program is run?

CS1010E Lecture 9 p.19/29

Random-Number Seed
Different sequences of random values are generated
with a different random-number seed using the
function srand (from stdlib.h).
The argument of the srand function is an (unsigned)
integer that is used in computations that initialize the
sequence; the seed value is not the first value in the
sequence.
The seed value is typically defined as a constant.
srand is generally executed once throughout the
execution of the program in the main function.

CS1010E Lecture 9 p.20/29

Random-Number Seed
#include <stdio.h>
#include <stdlib.h>
#define SEED 100
void printArray(int t[], int numElem);
int main(void)
{
int i, r, list[10];
srand(SEED);
for (i = 0; i < 10; i++)
list[i] = rand();
printArray(list,10);
return 0;
}

CS1010E Lecture 9 p.21/29

Time-based Seeding
Using the current time (in seconds) to seed
the random number generator.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // header file for time function
#define SEED (unsigned int)time(NULL) // current time
void printArray(int t[], int numElem);
int main(void)
{
int i, r, list[10];
srand(SEED);
for (i = 0; i < 10; i++)
list[i] = rand();
printArray(list,10);
return 0;
}
CS1010E Lecture 9 p.22/29

Integer Sequences
Generating random integers over a specified
range is simple with the rand function.
Suppose we want to generate random
integers between 0 and 7.
x = rand()%8;
Suppose we want to generate a random
integer between 25 and 25.
The total number of possible integers is 51.
x = rand()%51 - 25;

CS1010E Lecture 9 p.23/29

Integer Sequences
Function to generate and return an integer
between two specified integers, a and b.
int rand_int(int a,int b)
{
return rand()%(b-a+1) + a;
}

Seeding with srand must be done once in


main function first.

CS1010E Lecture 9 p.24/29

Floating-Point Sequences
The computation to convert an integer
between 0 and RAND_MAX to a floating-point
value between a and b has three steps.
The value from the rand function is first divided by
RAND_MAX to generate a floating-point value
between 0 and 1, i.e. 1.0*rand()/RAND_MAX
The value between 0 and 1 is then multiplied by
(b a) (the width of the interval [a, b]) to give a value
between 0 and (b a).
The value between 0 and (b a) is then added to a
to adjust it so that it will be between a and b.
CS1010E Lecture 9 p.25/29

Floating-Point Sequences
Function to generate and return a
floating-point number between a and b.
double rand_float(double a,double b)
{
return (1.0*rand()/RAND_MAX)*(b-a) + a;
}

The value of rand() needs to be converted


to a double value so that the result of the
division would be a double value.
Seeding with srand must be done once in
main function first.
CS1010E Lecture 9 p.26/29

Array of Structures
An array of fractions:
struct Fraction
{
int num, den;
};
...
struct Fraction fracArray[3] = {{1,4},{5,12}};
(fracArray[2]).num = 2;
(fracArray[2]).den = 1;

fracArray :

12

1
CS1010E Lecture 9 p.27/29

Problem Solving
A Farey Sequence of order n, denoted Fn , is the
sequence of reduced fractions between 0 and 1 having
denominators less than or equal to n, arranged in order
of increasing size. For example, F8 is the sequence


0 1 1 1 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 5 6 7 1
, , , , , , , , , , , , , , , , , , , , , ,
1 8 7 6 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 6 7 8 1

Main tasks:
Enumerate all possible fractions based on n.
Sort the sequence of fractions.
Remove duplicate fractions within the sequence.
Reduce fractions within the sequence.
CS1010E Lecture 9 p.28/29

Lecture Summary
Understand the technique of selection sort.
Application of sorting in a problem requires:
The type of the parameter (as well as temp
variable) to be modified.
The if condition to be altered.
Understand the techniques of search algorithms.
Random number generation
Integer/Floating-point sequences.
Expressions to scale and shift.
Since a structure behaves like a primitive, an array of
structures would behave like an array of primitives.
CS1010E Lecture 9 p.29/29

Das könnte Ihnen auch gefallen