Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to sort an array with a single loop in JavaScript

1 Answer

0 votes
/**
 * Sorts an array in-place in non-decreasing order using Gnome Sort.
 *
 * Algorithm Logic (Single Loop):
 * - Advances through the array using a single while loop index.
 * - Moves forward when adjacent elements are in correct relative order.
 * - When an out-of-order adjacent pair is encountered, swaps the elements
 *   and steps backward one index to verify order against preceding items.
 * - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
 * - Space Complexity: O(1) auxiliary space.
 *
 * @param {Array<number>} arr - The array to be sorted in place.
 * @returns {Array<number>} The sorted array reference.
 */
function singleLoopSort(arr) {
    let pos = 0;
    const len = arr.length;

    while (pos < len) {
        // Move forward if at index 0 or if adjacent pair is in correct order
        if (pos === 0 || arr[pos] >= arr[pos - 1]) {
            pos++;
        } else {
            // Swap adjacent out-of-order elements using array destructuring assignment
            [arr[pos], arr[pos - 1]] = [arr[pos - 1], arr[pos]];
            pos--;
        }
    }

    return arr;
}

/**
 * Main 
 */
function main() {
    const numbers = [42, -5, 12, 0, 89, -18, 33, 7];

    console.log("Original array:");
    console.log(numbers.join(" "));

    singleLoopSort(numbers);

    console.log("\nSorted array:");
    console.log(numbers.join(" "));
}

main();


/*
run:

Original array:
42 -5 12 0 89 -18 33 7

Sorted array:
-18 -5 0 7 12 33 42 89

*/

 



answered 15 hours ago by avibootz
...