I have implemented quickly the quick sort algorithm in JavaScript using prototype based style.
The code is rather short (http://jsfiddle.net/b8mfY/):
<script>
"use strict";
var Sort = function( inputArray ) {
this.arrayTest = undefined;
this.init( inputArray );
};
Sort.prototype.init = function( inputArray ) {
if ( inputArray instanceof Array && inputArray.length > 0 ) {
this.arrayTest = inputArray;
this.DumpArray( this.arrayTest );
this.QuickSort( this.arrayTest, 0, this.arrayTest.length - 1 );
this.DumpArray( this.arrayTest );
}
else console.log( 'Input argument isn\'t an array object or its length equals zero.' );
};
Sort.prototype.QuickSort = function( data, first, last ) {
var i = first;
var j = last;
var x = data[ Math.ceil( ( first + last ) / 2 ) ];
do {
while ( data[ i ] < x ) i++;
while ( data[ j ] > x ) j--;
if ( i <= j ) {
if ( i < j ) {
if ( data[ i ] !== data[ j ] ) {
var tempItem = data[ i ];
data[ i ] = data[ j ];
data[ j ] = tempItem;
}
}
i++;
j--;
}
} while ( i <= j );
if ( i < last ) this.QuickSort( data, i, last );
if ( first < j ) this.QuickSort( data, first, j );
}
Sort.prototype.DumpArray = function() {
var output = 'The content of array: [ ';
if ( this.arrayTest instanceof Array && this.arrayTest.length > 0 ) {
this.arrayTest.forEach( function( item ) {
output = output.concat( [ item, ', ' ].join( '' ) );
});
}
else console.log( 'Can\'t dump the input array. It\'s not an array object or its length equals zero.' );
output = output.substring( 0, output.length - 2 );
output = output.concat( ' ].' );
console.log( output );
};
window.onload = new Sort([
10,
1,
27,
4090,
100000,
2222,
4934
]);
</script>
I'm asking for a code review of the quick sort implementation part more than other details.