Home > Net >  Quick sorting array in JavaScript
Quick sorting array in JavaScript

Time:10-31

const arr = [5,3,2,6,1];

const quickSort = (arr) => {
  for(let j = 0; j < arr.length; j  ) {

    let index = null;
    let min = arr[0];

    for(let i = 0; i < arr.length; i  ) {
      if(arr[i] < min) {
        min = arr[i]
        index = i
      }
    }

    const tmp = arr[j]

    arr[0] = min;
    arr[index] = tmp
  }

  return arr;  
}


console.log(quickSort(arr), 'res')

In the code above i try to sort the array using the next logic:

  • i compare each array element with the first one and if it is lower than the first then i swap the array elements. Doing this i don't get the sorted array.
    Question: What is the issue with my code and how to fix it?

CodePudding user response:

Quick sort is a divide and conquer algorithm used for sorting. If you want to view more information about it visit the wikipedia site for quick sort. Your current code does what you told it to do, which is not sorting but as you said it is comparing each element with the first one and if it is smaller it swaps them. Now, if you want to sort an array just use the built-in sort function

arr.sort();

That should sort the array. If you want to built one on your own I would suggest to pick one that best suits you from the long list of sorts. If you are a beginner I would suggest you to try Bubble Sort or Selection Sort, but if you feel comfortable with writing code then Quick Sort or even Merge Sort could potentially be more suitable for you.

Edit: I looked at your code again and realised that you were trying to implement Selection sort. To fix it just use the following code:

const arr = [5,3,2,6,1];

const SelectionSort = (arr) => {
  for(let j = 0; j < arr.length; j  ) {

  let index = null;
  let min = arr[j];

  for(let i = j; i < arr.length; i  ) {
    if(arr[i] < min) {
      min = arr[i]
      index = i
    }
  }

  const tmp = arr[j]

  arr[j] = min;
  arr[index] = tmp
}

  return arr;  
}


console.log(SelectionSort(arr), 'res')

Your main mistake in the code was that you started everything from index 0, but you should have initialised everything from j because you are in a loop.

CodePudding user response:

const arr = [5,3,2,6,1];

const quickSort = (arr) => {
for(let j = 0; j < arr.length; j  ) {

    let index = j;
    let min = arr[j];

    for(let i = j 1; i < arr.length; i  ) {
        if(arr[i] < min) {
            min = arr[i]
            index = i
        }
    }

    let tmp = arr[j]

    arr[j] = min;
    arr[index] = tmp
}

return arr;  
}

  • Related