Skip to content

Instantly share code, notes, and snippets.

@houssemFat houssemFat/sort.js
Last active Nov 10, 2016

Embed
What would you like to do?
sorting algorithms
var a = [6, 5, 3, 1, 9, 7, 2, 4];
var length = a.length ;
bubbleSort = function (){
var swap = 0 ;
for (i = 0 ; i < length - i + 1 ; i++){
for (var j = 1 ; j < length - i ; j++) {
if (a[j-1] > a[j] ){
console.log ("moving " + a[j-1])
swap = a[j] ;
a[j] = a[j-1] ;
a[j-1] = swap;
}
}
console.log (a);
}
}
var a = [6, 5, 3, 1, 9, 7, 2, 4];
function _swap(part, swapWith, me){
var swap = part[me] ;
part[me] = part[swapWith] ;
part[swapWith] = swap;
return part ;
}
function _splice(array, from, to){
var _array = [];
for (var i= from ; i < to ; i++){
_array.push(array[i]);
}
return _array;
}
function qucikSort (array, from, to){
//console.log (">>>>>>>>>>>>>>" + array)
var length = array.length ;
if (length < 2){
return array ;
}
var pivot = array[length -1];
//console.log (">>>>>>pivot>>>>>>>> " + pivot )
var swapPosition = from - 1;
for (var i=from ; i < to -1 ; i++){
if (array[i] < pivot){
swapPosition += 1 ;
array = _swap (array, swapPosition, i)
console.log(array)
}
}
array = _swap(array, swapPosition + 1 , to - 1)
var left = _splice(array, 0 , swapPosition + 1) ;
console.log('left');
console.log(left);
var right = _splice(array, swapPosition + 2 , array.length) ;
console.log('right');
console.log(right);
return qucikSort(left, 0, left.length).concat(pivot, qucikSort(right, 0, right.length));
}
A = qucikSort (a, 0, a.length);
/**
* alt
* http://www.stoimen.com/blog/2010/07/09/friday-algorithms-javascript-bubble-sort/
* http://www.stoimen.com/blog/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/
*/
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
function bubbleSort(a)
{
var swapped;
do {
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
bubbleSort(a);
console.log(a)
/**
*
*/
var a = [2,4,5,63,4,5,63,2,4,43];
function quicksort(arr)
{
if (arr.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
console.log(quicksort(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.