Documente Academic
Documente Profesional
Documente Cultură
CS1010E Lecture 9
Problem Solving With
One Dimensional Arrays
Henry Chia
hchia@comp.nus.edu.sg
Lecture Outline
Selection Sort
Selection sort
Searching
Linear search
Binary search
Array of Structures
Selection Sort
Original order:
5 3 12 8 1
Selection Sort
void selectionSort(int list[],int numElem)
{
int i, j, minIndex, temp;
}
return;
}
Selection Sort
Selection Sort
Search Algorithms
Linear Search
Binary Search
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;
}
Binary Search
Binary Search
14
lr
m
38
52
77
14 < 25:
-7 2 14
r
m
38
l
52
77
105
105
105
14 = 14 so it is found!
CS1010E Lecture 9 p.13/29
Binary Search
Binary Search
14
lr
m
38
52
77
105
if (list[mid] == value)
index = mid;
else
if (list[mid] > value)
right = mid - 1;
else
left = mid + 1;
105
}
return index;
}
Random Numbers
Random Numbers
int main(void)
{
int i, r, list[10];
for (i=0; i<10; i++)
list[i] = rand();
printArray(list,10);
return 0;
}
return;
}
Random Numbers
Random-Number Seed
Integer Sequences
Random-Number Seed
#include <stdio.h>
#include <stdlib.h>
#define SEED 100
srand(SEED);
for (i = 0; i < 10; i++)
list[i] = rand();
printArray(list,10);
return 0;
}
Time-based Seeding
Integer Sequences
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
Floating-Point Sequences
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
Floating-Point Sequences
Problem Solving
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.
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