Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my sort implementation not work?

I’m trying to sort an integer array without using sort function. I know there are other solutions available on Stack Overflow. I want to know what is wrong with my code. It performs ascending sort except for the first number in the array.

let arr = [2,4,5,1,3,7];
let iterable = true;
let iterationCount = 0;

while(iterable) {
 for(var i=iterationCount;i<=arr.length;i++) {
    if (arr[i] > arr[i+1]) {
      let temp=arr[i];
      arr[i]=arr[i+1];
      arr[i+1]=temp;
    }
 }
 iterationCount++;
 if (iterationCount == arr.length) {
    iterable = false;
 }
}

console.log(arr)

The output is [2, 1, 3, 4, 5, 7] while it should be [1, 2, 3, 4, 5, 7].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could change the outer loop for keeping the last index for checking and iterate until before the last index, because in the first inner loop, the max value is now at the greatest index and any further iteration do not need to check the latest last item.

let array = [2, 4, 5, 1, 3, 7],
    iterationCount = array.length;

while (iterationCount--) {
    for (let i = 0; i < iterationCount; i++) {
        if (array[i] > array[i + 1]) {
            let temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }
}

console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading