graemeboy
graemeboy

Reputation: 610

Quicksort in Javascript Bug

Hoping to get some help with this Quicksort algorithm in Javascript (it's not for homework or anything, just fun) - it's not working and I'm not sure where I'm going wrong.

function quicksort ( arr ) {
        // Launch the sorting process.
        sort(arr, 0, arr.length - 1 );

        /**
         * swap
         * takes in an array and two indexes,
         * swaps the elements in the array at those indexes
         */
        function swap ( arr, a, b ) {
            var temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }

        function partition ( arr, l, r) {
            var p = arr[r],
                i = l - 1,
                j = l;
            while ( j < r - 1) {
                if (arr[j] <= p) {
                    swap ( arr, ++i, j );
                }
                j++;
            }

            swap (arr, i + 1, r);
            return i + 1;
        }

        function sort ( arr, l, r ) {
            var p;
            if (l < r) {
                p = partition( arr, l, r );
                sort( arr, l, p - 1);
                sort( arr, p + 1, r);
            } else {
                console.log(arr);    
            }
        }
    }

Upvotes: 0

Views: 101

Answers (1)

graemeboy
graemeboy

Reputation: 610

Okay, I think I found it. The problem as just in my partition loop, I was ending it too early. Here is the complete code:

  function quicksort ( arr ) {
        // Launch the sorting process.
        sort(arr, 0, arr.length - 1 );

        /**
         * swap
         * takes in an array and two indicies,
         * swaps the elements in the array at those indicies
         */
        function swap ( arr, a, b ) {
            var temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }

        function partition ( arr, l, r) {
            var p = arr[r],
                i = l - 1,
                j = l;
            while ( j < r) {
                if (arr[j] <= p) {
                    swap ( arr, ++i, j );
                }
                j++;
            }
            // Put the pivot in its correct place
            swap (arr, i + 1, r);
            return i + 1;
        }

        function sort ( arr, l, r ) {
            var p;
            if (l < r) {
                p = partition( arr, l, r );
                sort( arr, l, p - 1);
                sort( arr, p + 1, r);
            } else if (l === arr.length) {
                // Output the sorted array.
                console.log(arr);    
            }
        }
    }

Basic tests:

quicksort( [19,12,1,2,3,123,23,2,5] ) [ 1, 2, 2, 3, 5, 12, 19, 23, 123 ]

quicksort( [8,3,2,1,5,1,3] ) [ 1, 1, 2, 3, 3, 5, 8 ]

Open to suggestions on how to improve! :)

Upvotes: 1

Related Questions