Skip to content

Instantly share code, notes, and snippets.

@kolosovsky
Last active May 17, 2018 13:52
Show Gist options
  • Save kolosovsky/9b31b85bcd93d0ee79ea247971ef61bf to your computer and use it in GitHub Desktop.
Save kolosovsky/9b31b85bcd93d0ee79ea247971ef61bf to your computer and use it in GitHub Desktop.
Sorting algorithms in JavaScript

Sorting algorithms in JavaScript

var i = -1,
	arr1 = [],
	arr2 = [],
	arr3 = [],
	arr4 = [],
	randomNumber;

while (i++ < 10000) {
	randomNumber = Math.round(Math.random() * 100);

	arr1.push(randomNumber);
	arr2.push(randomNumber);
	arr3.push(randomNumber);
	arr4.push(randomNumber);
}

/* === SELECTION SORT === */

function selectionSort(arr) {
	var index = -1,
		l = arr.length,
		innerLoopIndex,
		min,
		indexOfMin;

	while (++index < l - 1) {
		min = arr[index];
		indexOfMin = index;

		innerLoopIndex = index - 1;

		while (++innerLoopIndex < l) {
			if (arr[innerLoopIndex] < min) {
				min = arr[innerLoopIndex];
				indexOfMin = innerLoopIndex;
			}
		}

		if (index !== indexOfMin) {
			arr[indexOfMin] = arr[index];
			arr[index] = min;
		}
	}

	//return arr;
}

console.time('Selection sort');
console.log(selectionSort(arr1));
console.timeEnd('Selection sort');


/* === BUBBLE SORT === */

function bubbleSort(arr) {
	var isNextLoopNeeded = true,
		sortedElementNum = 0,
		l = arr.length,
		i, temp;

	while (isNextLoopNeeded) {
		isNextLoopNeeded = false;
		i = 0;

		while (i < l - 1 - sortedElementNum) {
			if (arr[i] > arr[i + 1]) {
				temp = arr[i];
				arr[i] = arr[i + 1];
				arr[i + 1] = temp;

				isNextLoopNeeded = true;
			}

			i++;
		}

		sortedElementNum++;
	}

	//return arr;
}


console.time('Bubble sort');
console.log(bubbleSort(arr2));
console.timeEnd('Bubble sort');


/* === INSERTION SORT === */

function insertionSort(arr) {
	var l = arr.length,
		i = 1,
		currentItem,
		j;

	while (i < l) {
		currentItem = arr[i];
		j = i - 1;

		while (j > -1) {
			if (currentItem < arr[j]) {
				arr[j + 1] = arr[j];
				arr[j] = currentItem;
			} else {
				break;
			}

			j--;
		}

		i++;
	}

	//return arr;
}


console.time('Insertion sort');
console.log(insertionSort(arr3));
console.timeEnd('Insertion sort');

console.time('Native JS sort');
arr4.sort(function(a, b) {
	return a - b;
});
console.timeEnd('Native JS sort');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment