Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

sort elements using quick sort and merge two sorted array elements.

 function quickSort(arr) {

  if (arr.length <= 1) {

    return arr;

  }

 

  const pivot = arr[0];

  const left = [];

  const right = [];

 

  for (let i = 1; i < arr.length; i++) {

    if (arr[i] < pivot) {

      left.push(arr[i]);

    } else {

      right.push(arr[i]);

    }

  }

 

  return quickSort(left).concat(pivot, quickSort(right));

}

 

function mergeSortedArrays(arr1, arr2) {

  let result = [];

  let i = 0;

  let j = 0;

 

  while (i < arr1.length && j < arr2.length) {

    if (arr1[i] <= arr2[j]) {

      result.push(arr1[i]);

      i++;

    } else {

      result.push(arr2[j]);

      j++;

    }

  }

 

  while (i < arr1.length) {

    result.push(arr1[i]);

    i++;

  }

 

  while (j < arr2.length) {

    result.push(arr2[j]);

    j++;

  }

 

  return result;

}

 

const unsortedArray = [3, 5, 2, 1, 4];

const sortedArray = quickSort(unsortedArray);

 

const arr1 = [1, 3, 5];

const arr2 = [2, 4, 6];

const mergedArray = mergeSortedArrays(arr1, arr2);

 

console.log(sortedArray);

console.log(mergedArray);

 

Output:-

[1, 2, 3, 4, 5]

[1, 2, 3, 4, 5, 6]

Post a Comment

0 Comments

Ad Code

Responsive Advertisement