4

I am new to JavaScript, and I have an array which contains numbers.

 var arr = [2,4,8,1,5,9,3,7,6];

How can I sort it using a native for loop in JavaScript?

I know sort function is available, but I want it through for loop.

The output should be:

 var res = [1,2,3,4,5,6,7,8,9];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rj-s
  • 484
  • 3
  • 7
  • 17
  • 2
    *"using For loop"* - A single for loop, no nested loops or recursion? Is this homework, and you just want some guidance to get started? (I can't think why else you'd want to avoid the built in `.sort()` function.) – nnnnnn Jul 12 '16 at 14:03
  • 2
    There are any number of sorting algorithms you can implement... https://en.wikipedia.org/wiki/Sorting_algorithm There's no one answer here. The *practical real world answer* is `arr.sort()`. – deceze Jul 12 '16 at 14:04
  • @Bob Deckard: What is the canonical Stack Overflow question for that gotcha? – Peter Mortensen Jan 24 '23 at 18:03
  • Some low-scored duplicates for the number-as-string gotcha (search engines are really broken nowadays): *[How to sort strings in JavaScript numerically](https://stackoverflow.com/questions/8107226/how-to-sort-strings-in-javascript-numerically)* (2010), *[How can I sort a string of numbers in JavaScript?](https://stackoverflow.com/questions/65051628/how-to-sort-string-of-numbers-in-javascript)* (2020), and *[JavaScript: Sort an array of String numbers](https://stackoverflow.com/questions/51560507/javascript-sort-an-array-of-string-numbers)* (2018). – Peter Mortensen Jan 24 '23 at 18:12
  • A false positive (about strings, with some numbers in them): *[Natural sort of alphanumerical strings in JavaScript](https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings)* – Peter Mortensen Jan 24 '23 at 18:14

11 Answers11

19

var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];

for (var i = 1; i < Arr.length; i++)
    for (var j = 0; j < i; j++)
        if (Arr[i] < Arr[j]) {
            var x = Arr[i];
            Arr[i] = Arr[j];
            Arr[j] = x;
        }

console.log(Arr);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Holger
  • 899
  • 2
  • 7
  • 12
  • 3
    This ***unexplained*** answer [earned](https://stackoverflow.com/help/badges/8842/lifeboat?page=1) the OP a *Lifeboat* badge. What is it? [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort)? What is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/38331533/edit), not here in comments (* ***without*** * "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jan 24 '23 at 17:17
3

I would do something like this...

var input = [2,3,8,1,4,5,9,7,6];

var output = [];
var inserted;

for (var i = 0, ii = input.length ; i < ii ; i++){
  inserted = false;
  for (var j = 0, jj = output.length ; j < jj ; j++){
    if (input[i] < output[j]){
      inserted = true;
      output.splice(j, 0, input[i]);
      break;
    }
  }

  if (!inserted)
    output.push(input[i])
}

console.log(output);

Maybe there are more efficient ways, but if you want to use the for loop, it's my first idea...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
R. Foubert
  • 633
  • 4
  • 8
0

First create an empty array where the sorted numbers will be pushed into.

let sorted = [];

Secondly, create a very large amount of numbers that none of the numbers of the array can match. This number will be used for the very first comparison to determine which number of the array is smaller.

let comparison = 9000000000;

Create a for loop.

This loop will have another loop inside of it. The inner loop will check for the smallest number in a given array, and once the smallest number is gotten, it will be push into the empty array we created. The smallest number will also be removed from the initial array and then the array will run again.

for(a = 0; a < arr.length; a++){

    //This inner loop fetches the smallest number.
    for(b = 0; b < arr.length; a++){
        if(comparison > arr[b]){
            comparison = arr[b];
        }
    }

    // The smallest number is assigned to comparison
    // Now it being pushed to the empty array
    sorted.push(comparison);

    // Remove the smallest number from the initial array

    let indexOfSmallNumber = arr.indexOf(comparison);
    arr.splice(indexOfSmallNumber, 1);

    // Set the comparison back to 9000000000;
    comparison = 90000000000;

    a = -1;
    // Here, "a" is our main loop index counter and we are
    // setting it to -1 because we don't want it to change
    // to 2 by default, doing this will make the loop run
    // forever until the initial array is empty.
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
let arr = [4, 2, 5, 1]
let temp;

function converter(arr) {

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

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

      if(arr[i] > arr[j]) {

        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
      }
    }
  }
  return arr
}

const newArr = converter(arr)
console.log(newArr)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    Your answer could be improved with additional supporting information. Please edit your answer to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – Syscall Jan 31 '22 at 08:26
  • This is a repeat of at least one previous answer. What is it? [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort)? – Peter Mortensen Jan 24 '23 at 17:35
0

Use:

let s = [4, 6, 3, 1, 2];
for (let i = 0; i < s.length;) {
    if (s[i] > s[i + 1]) {
        let a = s[i];
        s[i] = s[i + 1];
        s[i + 1] = a;
        i--;
    }
    else {
        i++;
    }
}

This is a sorting algorithm which has a best time complexity of O(n) and the worst time of O(n^2).

This code checks for each number, and then compares to all numbers on the left side.

To check the time it takes each code to run, you can also use this code below:

let start = process.hrtime.bigint()
let end = process.hrtime.bigint()

console.log(end - start) // This measures the time used in nano seconds.

Also for microseconds, you can use this performance.now().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    [Please do not post an answer that consists essentially of code](https://stackoverflow.com/questions/how-to-answer). Please [edit] your answer to include an explanation of how and why the code solves the problem, when it should be used, what its limitations are, and if possible a link to relevant documentation. – ljmc Jan 07 '23 at 21:36
  • Re *"a sorting algorithm"*: Which one? [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort)? – Peter Mortensen Jan 24 '23 at 17:50
  • This seems like a ***completely bogus answer.*** How can it sort the array in one pass? By pure luck with the example array? I don't think it will work with the example from the question, `[2, 4, 8, 1, 5, 9, 3, 7, 6]`. – Peter Mortensen Jan 24 '23 at 17:57
  • @PeterMortensen have you tried running the code. it works like magic. try running any array and you will see that it sort it – abdullah ajibade Jan 25 '23 at 03:19
  • 1
    An interesting approach, but it needs (at least) 2 changes to avoid reading beyond the array bounds: he upper terminating condition should be `i < s.length - 1`, and the `i--` should have a guard to prevent it becoming -ve – Alistair Ward Jan 31 '23 at 22:48
  • It is a weird *for* loop. It increases and decreases the loop variable `i`. It would be better to express it as a 'while' loop. Is it a very convoluted bubble sort? Somebody trying to be clever by implementing bubble sort with one loop? At least it should be explained in the answer. – Peter Mortensen Feb 04 '23 at 00:37
0

Here there is a very simple solution that uses a temporary array to store the values greater than the current one. Then it puts the current value between the lesser and the greater values:

var arr = [2,4,8,1,5,9,3,7,6];
var res = [];
for (const c of arr) {
    let tmp = [];
    while (c < res[res.length-1]) {
        tmp.unshift(res.pop());
    }
    res = [...res, c, ...tmp];
} 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rafaelmi
  • 164
  • 1
  • 6
-1

Under the JavaScript array sort section of W3Schools it talks about how to compare a value in an array with the others and then order them based on the values being returned. I updated the code to use a for loop to sort values.

// Ascending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
    points.sort(function (a, b) {
        return a - b
    });
    output += points[i] + "<br>";
}
console.log(output);

// Descending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
    points.sort(function (a, b) {
        return b - a
    });
    output += points[i] + "<br>";
}
console.log(output);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
WELCHDK
  • 1
  • 1
  • Since this question was based specifically on JavaScript, I didn't include the complementary HTML, so I realize that this results in only one line on the console. – WELCHDK Dec 31 '19 at 03:52
  • It's long time ago, but... you are sorting and sorting again, every loop. You only need `points.sort(function(a,b) { return a-b }); console.log(points); `. But this answer is not helpful because the question contained "using native For Loop". – Holger May 31 '22 at 12:38
-1

for (let i = 0; i < numbers.length; i++) {
  for (let j = i + 1; j < numbers.length; j++) {
    if (numbers[i] > numbers[j]) {
      const temp = numbers[i];
      numbers[i] = numbers[j];
      numbers[j] = temp;
    }
  }
}
sabarinath
  • 39
  • 9
  • 3
    Above logic will not work with example `[4, 6, 3, 1, 2]`. – dipenparmar12 Nov 25 '22 at 14:31
  • Is it bubble sort? The swap operation is broken. Only [a fancy XOR operation](https://en.wikipedia.org/wiki/XOR_swap_algorithm) can avoid the temporary variable. Why is this upvoted? – Peter Mortensen Jan 24 '23 at 17:37
  • `for (let i = 0; i < numbers.length; i++) { for (let j = i + 1; j < numbers.length; j++) { if (numbers[i] > numbers[j]) { const temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } } }` – sabarinath Mar 05 '23 at 15:39
-1
const array = [12, 3, 45, 61, 23, 45, 6, 7];

function sortArray(array) {
    for (var i = 0; i < array.length; ++i) {
        for (var j = 0; j < array.length - 1 - i; ++j) {
            if (array[j] > array[j + 1]) {
                [array[j], array[j + 1]] = [array[j + 1], array[j]];
            }
        }
    }
    return array;
}

console.log(sortArray(array));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    Try to add some comments and additional information that can be helpful in understanding the code. This will help a person to evaluate between different answers easily. – Neel Aug 23 '22 at 16:16
  • An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/73415798/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jan 24 '23 at 17:42
-1

Here are the two solutions for the same algorithm:

Solution 1:

We can directly use JavaScript functions:

let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]

const changeOrder = (arr) => {
    return arr.sort((a, b) => a - b)
}

let result = changeOrder(arr);

console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Solution 2:

We can use a JavaScript for loop for doing the same

let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]

const changeOrder = (arr) => {
    for(let i=1; i< arr.length; i++) {
        for(let j=0; j < i; j++) {
            if(arr[i] < arr[j]) {
                let x = arr[i]
                arr[i] = arr[j]
                arr[j] = x
            }
        }
    }
    return arr;
}

let result = changeOrder(arr);
console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rahul Mishra
  • 4,263
  • 7
  • 32
  • 53
-1
const numberArr = [5, 9, 2, 8, 4, 10, 1, 3, 7, 6];

function sortedFunction(arr) {
  let sortedArr = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      let n = 0;
      if (arr[i] > arr[j]) {
        n = arr[i];
        arr[i] = arr[j];
        arr[j] = n;
      }
    }
    sortedArr.push(arr[i]);
  }
  return sortedArr;
}
sortedFunction(numberArr);

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 09 '22 at 07:20