2021-03-14
slides.com/jod/pt_11a
Docent: Jo Devriendt
Assistent: Ann Philips
Coördinator: Joost Vennekens
voornaam.achternaam@kuleuven.be
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
Input: sequentie sorteerbare elementen
Output: gesorteerde sequentie
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
Overzicht:
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
void swap(int* x, int* y){
int tmp = *x;
*x = *y;
*y = tmp;
}
void selection(int a[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[i]) {
swap(&a[i],&a[j]);
}
}
}
}
Vind kleinste element in a[i..n], stockeer in a[i]
Herhaal voor steeds kleinere restarrays
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
#define N 8
int main() {
int a[N] = {5,3,1,7,2,6,4,5};
selection(a, N);
for (int i = 0; i < N; ++i) {
printf("%d ", a[i]);
}
printf("\n");
}
$ ./a.out
1 2 3 4 5 5 6 7
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021
void swap(int* x, int* y){
int tmp = *x;
*x = *y;
*y = tmp;
}
void selection(int a[], int n) {
for (int i = 0; i < n - 1; ++i){
for (int j = i+1; j < n; ++j){
if (a[j] < a[i]) {
swap(&a[i],&a[j]);
}
}
}
}
Aantal keren door de binnenste for-loop:
Dat kan beter :)
Programmeertechnieken [B-KUL-YI0855]
De Nayer, IIW, E-ICT, 2Ba + schakel, 2020-2021