Array logics
Array logics:
1. Write a program to print the smallest number in an array?
function lowestElement(arr) {
for (let j = arr.length-1; j > 0; j--) {
if(arr[j] < arr[j-1]) {
var temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
console.log(arr[0]);
}
The above program is based on the bubble sorting logic, sending the lower element to first place.
function smallestNumberWithSelectionSort(arr) {
var lowest = 0;
for (let i = 1; i < arr.length; i++) {
if(arr[i] < arr[lowest]) {
lowest = i;
}
}
if(lowest !== 0) {
var temp = arr[lowest];
arr[lowest] = arr[0];
arr[0] = temp;
}
console.log(arr);
}
smallestNumberWithSelectionSort([34, 22, 12, 44, 9, 99]);
lowestElement([5,1,2,3,4]);
2. Write a program to print the largest number in an array?
function highestElement(arr) {
for (let j = 1; j < arr.length; j++) {
if(arr[j] > arr[j+1]) {
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
console.log(arr[arr.length-1]);
}
The above program is based on the bubble sorting logic, sending the large element to the last place.
highestElement([12,22,33,1,2,3,99,4,5,6]);
3. Write a program to merge two sorted arrays?
This is for sorted arrays only
function mergeSortedArrays(arr1, arr2) {
let mergedArray = [];
let i = 0;
let j = 0;
// take 2 arrays in a loop
while (i < arr1.length && j < arr2.length) {
// Compare it's index elements and push the lower element to result array and increase the index of array, which we have taken element from
if(arr1[i] < arr2[j]) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}
// If the 2 arrays are not same in length, then we need to push remaining elements to list
while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}
while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}
console.log(mergedArray);
}
mergeSortedArrays([1,2,3,13, 5], [6,7,8,9]);
Comments
Post a Comment