switchMaxMin-Java Script

I have to write a function switchMaxMin(tab, n) that swaps the maximum element with the minimum element in an n-element array tab. We assume that all elements of the array are distinct (i. e. there are not a few maxima or minima). I don’t know how to do this
I started to write the code and I came up with this:

var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = tab[0];
var max = tab[0];
document.write("Tablica: ");
for (i = 1; i < tab.length; i++) {
  document.write(tab[i] + ", ");
  if (min > tab[i]) {
    min = tab[i];
  }
  if (max < tab[i]) {
    max = tab[i];
  }
}
document.write("<br /><br />Max: " + max);
document.write("<br />Min: " + min);

7 thoughts on “switchMaxMin-Java Script”

  1. var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
    
    tab.sort(function(a, b) { //Sort Array from low to high
      return a - b;
    });
    var min = tab[0]; //First index value
    var max = tab[tab.length-1]; //Last index value
    
    tab.splice(tab.length-1, 1,min); //Insert min at last index and delete one element
    tab.splice(0,1,max); //Insert max at index 0 and delete one element
    
    console.log(tab);
    Reply
  2. To swap the elements you have also to store the indices of the max and min elements

    if (min > tab[i]) {
        min = tab[i];
        minIndex = i;
      }
      if (max < tab[i]) {
        max = tab[i];
        maxIndex = i;
      } 
    

    Then you can reassign it by a classical swap function

    function swapper(maxInd, minInd) {
      let temp = tab[maxInd];
      tab[maxInd] = tab[minInd]
      tab[minInd] = temp;
    }
    
    var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
    var min = tab[0];
    var max = tab[0];
    var minIndex = 0;
    var maxIndex = 0;
    document.write("Tablica: ");
    for (let i = 0; i < tab.length; i++) {
      document.write(tab[i] + ", ");
      if (min > tab[i]) {
        min = tab[i];
        minIndex = i;
      }
      if (max < tab[i]) {
        max = tab[i];
        maxIndex = i;
      }
    }
    
    swapper(maxIndex, minIndex);
    
    document.write("<br /><br />Max: " + max);
    document.write("<br />Min: " + min);
    
    document.write("<br /> After the swap " + tab.join(","));
    
    function swapper(maxInd, minInd) {
      let temp = tab[maxInd];
      tab[maxInd] = tab[minInd]
      tab[minInd] = temp;
    }
    Reply

Leave a Comment