71 lines
2.0 KiB
HTML
71 lines
2.0 KiB
HTML
<!doctype html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>Übung 8: Rekursive Suche des Maximums in einem Array</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<div class="container py-5">
|
|
<div class="alert alert-primary">
|
|
<h2>Übung 8: Rekursive Suche des Maximums in einem Array</h2>
|
|
<p>
|
|
Schreibe eine rekursive Funktion in JavaScript, die das größte Element in einem Array von Zahlen findet.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</main>
|
|
<script>
|
|
'use strict';
|
|
|
|
const findMax2 = (ar) => {
|
|
if (ar.length === 0) return null;
|
|
if (ar.length === 1) return ar[0];
|
|
let max = ar[0];
|
|
let i = -1;
|
|
while (++i < ar.length) {
|
|
if (ar[i] > max) {
|
|
max = ar[i];
|
|
}
|
|
}
|
|
return max;
|
|
};
|
|
|
|
const findMax = (arr) => {
|
|
// Basisfall
|
|
if (arr.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
if (arr.length === 1) {
|
|
return arr[0];
|
|
}
|
|
|
|
return Math.max(arr[0], findMax(arr.slice(1))); // Rekursion
|
|
|
|
// return arr.length === 0 ? null : arr.length === 1 ? arr[0] : Math.max(arr[0], findMax(arr.slice(1)));
|
|
};
|
|
|
|
// Test cases
|
|
console.time('rekursion max');
|
|
console.log(findMax([1, 5, 3])); // => 5
|
|
console.timeEnd('rekursion max');
|
|
|
|
console.time('Math.max');
|
|
console.log(Math.max(...[1, 5, 3]));
|
|
console.timeEnd('Math.max');
|
|
|
|
console.time('for');
|
|
console.log(findMax2([1, 5, 3]));
|
|
console.timeEnd('for');
|
|
|
|
console.log(findMax([1, 5, 3, 9, 2])); // => 9
|
|
console.log(findMax([-10, -20, -3, -4])); // => -3
|
|
console.log(findMax([42])); // => 42
|
|
console.log(findMax([])); // => null
|
|
</script>
|
|
</body>
|
|
</html>
|