Skip to content

Data Structures/Graph and Sorting files #141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Data Structures/Graph/Graph.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

class Graph {
constructor () {
this.adjacencyMap = {}
Expand Down Expand Up @@ -42,3 +41,4 @@ const example = () => {
g.addEdge(1, 3)
g.printGraph()
}
example()
105 changes: 52 additions & 53 deletions Sorts/TopologicalSort.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,59 @@

function TopologicalSorter() {
var graph = {},
isVisitedNode,
finishTimeCount,
finishingTimeList,
nextNode;

this.addOrder = function (nodeA, nodeB) {
nodeA = String(nodeA);
nodeB = String(nodeB);
graph[nodeA] = graph[nodeA] || [];
graph[nodeA].push(nodeB);
}

this.sortAndGetOrderedItems = function () {
isVisitedNode = Object.create(null);
finishTimeCount = 0;
finishingTimeList = [];

for (var node in graph) {
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
dfsTraverse(node);
}
}

finishingTimeList.sort(function (item1, item2) {
return item1.finishTime > item2.finishTime ? -1 : 1;
});

return finishingTimeList.map(function (value) { return value.node })
function TopologicalSorter () {
var graph = {}
var isVisitedNode
var finishTimeCount
var finishingTimeList
var nextNode

this.addOrder = function (nodeA, nodeB) {
nodeA = String(nodeA)
nodeB = String(nodeB)
graph[nodeA] = graph[nodeA] || []
graph[nodeA].push(nodeB)
}

this.sortAndGetOrderedItems = function () {
isVisitedNode = Object.create(null)
finishTimeCount = 0
finishingTimeList = []

for (var node in graph) {
if (Object.prototype.hasOwnProperty.call(graph, node) && !isVisitedNode[node]) {
dfsTraverse(node)
}
}

function dfsTraverse(node) {
isVisitedNode[node] = true;
if (graph[node]) {
for (var i = 0; i < graph[node].length; i++) {
nextNode = graph[node][i];
if (isVisitedNode[nextNode]) continue;
dfsTraverse(nextNode);
}
}

finishingTimeList.push({
node: node,
finishTime: ++finishTimeCount
});
finishingTimeList.sort(function (item1, item2) {
return item1.finishTime > item2.finishTime ? -1 : 1
})

return finishingTimeList.map(function (value) { return value.node })
}

function dfsTraverse (node) {
isVisitedNode[node] = true
if (graph[node]) {
for (var i = 0; i < graph[node].length; i++) {
nextNode = graph[node][i]
if (isVisitedNode[nextNode]) continue
dfsTraverse(nextNode)
}
}
}

finishingTimeList.push({
node: node,
finishTime: ++finishTimeCount
})
}
}

/* TEST */
var topoSorter = new TopologicalSorter();
topoSorter.addOrder(5, 2);
topoSorter.addOrder(5, 0);
topoSorter.addOrder(4, 0);
topoSorter.addOrder(4, 1);
topoSorter.addOrder(2, 3);
topoSorter.addOrder(3, 1);
console.log(topoSorter.sortAndGetOrderedItems());
var topoSorter = new TopologicalSorter()
topoSorter.addOrder(5, 2)
topoSorter.addOrder(5, 0)
topoSorter.addOrder(4, 0)
topoSorter.addOrder(4, 1)
topoSorter.addOrder(2, 3)
topoSorter.addOrder(3, 1)
console.log(topoSorter.sortAndGetOrderedItems())
95 changes: 47 additions & 48 deletions Sorts/bubblesort.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,65 @@
/*Bubble Sort is a algorithm to sort an array. It
/* Bubble Sort is a algorithm to sort an array. It
* compares adjacent element and swaps thier position
* The big O on bubble sort in worst and best case is O(N^2).
* The big O on bubble sort in worst and best case is O(N^2).
* Not efficient.
*/
function bubbleSort(items) {
let length = items.length;
for (let i = (length - 1); i > 0; i--) {
//Number of passes
for (let j = (length - i); j > 0; j--) {
//Compare the adjacent positions
if (items[j] < items[j - 1]) {
//Swap the numbers
let tmp = items[j];
items[j] = items[j - 1];
items[j - 1] = tmp;
}
}

function bubbleSort (items) {
const length = items.length
for (let i = (length - 1); i > 0; i--) {
// Number of passes
for (let j = (length - i); j > 0; j--) {
// Compare the adjacent positions
if (items[j] < items[j - 1]) {
// Swap the numbers
const tmp = items[j]
items[j] = items[j - 1]
items[j - 1] = tmp
}
}
}
}

//Implementation of bubbleSort
// Implementation of bubbleSort

var ar=[5,6,7,8,1,2,12,14];
//Array before Sort
console.log("-----before sorting-----")
console.log(ar);
bubbleSort(ar);
//Array after sort
console.log("-----after sorting-----")
console.log(ar);
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log('-----before sorting-----')
console.log(ar)
bubbleSort(ar)
// Array after sort
console.log('-----after sorting-----')
console.log(ar)

/*alternative implementation of bubble sort algorithm.
/* alternative implementation of bubble sort algorithm.
Using a while loop instead. For educational purposses only
*/
/*
*In bubble sort, we keep iterating while something was swapped in
*the previous inner-loop iteration. By swapped I mean, in the
*inner loop iteration, we check each number if the number proceeding
*the previous inner-loop iteration. By swapped I mean, in the
*inner loop iteration, we check each number if the number proceeding
*it is greater than itself, if so we swap them.
*/

function bubbleSort(arr){
let swapped = true;
while(swapped){
swapped = false;
for(let i = 0; i < arr.length-1; i++){
if(arr[i] > arr[i + 1]){
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
function alternativeBubbleSort (arr) {
let swapped = true
while (swapped) {
swapped = false
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
const temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
swapped = true
}
}
return arr;
}
return arr
}

//test
console.log("-----before sorting-----")
var array = [10,5,3,8,2,6,4,7,9,1];
console.log(array);
console.log("-----after sorting-----")
console.log(bubbleSort(array));


// test
console.log('-----before sorting-----')
var array = [10, 5, 3, 8, 2, 6, 4, 7, 9, 1]
console.log(array)
console.log('-----after sorting-----')
console.log(alternativeBubbleSort(array))
4 changes: 3 additions & 1 deletion Sorts/bucketSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ function bucketSort (list, size) {
}
return sorted
}

// Testing
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log(arrOrignal)
arrSorted = bucketSort(arrOrignal)
const arrSorted = bucketSort(arrOrignal)
// Array after sort
console.log(arrSorted)
3 changes: 2 additions & 1 deletion Sorts/combSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ elements goes down (for each iteration of outer loop) in steps of
a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ].

*/

function combSort (list) {
if (list.length === 0) {
return list
Expand Down Expand Up @@ -45,6 +46,6 @@ function combSort (list) {
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log(arrOrignal)
arrSorted = combSort(arrOrignal)
const arrSorted = combSort(arrOrignal)
// Array after sort
console.log(arrSorted)
9 changes: 5 additions & 4 deletions Sorts/cycleSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ number of writes to the original array, unlike any other in-place sorting
algorithm. It is based on the idea that the permutation to be sorted can
be factored into cycles, which can individually be rotated to give a sorted result.
*/

function cycleSort (list) {
let writes = 0
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
Expand All @@ -18,11 +19,11 @@ function cycleSort (list) {
}
}
// if its the same continue
if (position == cycleStart) {
if (position === cycleStart) {
continue
}

while (value == list[position]) {
while (value === list[position]) {
position++
}

Expand All @@ -32,14 +33,14 @@ function cycleSort (list) {
writes++

// rotate the rest
while (position != cycleStart) {
while (position !== cycleStart) {
position = cycleStart
for (let i = cycleStart + 1; i < list.length; i++) {
if (list[i] < value) {
position++
}
}
while (value == list[position]) {
while (value === list[position]) {
position++
}
const oldValueCycle = list[position]
Expand Down
1 change: 1 addition & 0 deletions Sorts/heapSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* key (the value) of node P is greater than the key of node C"
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
*/

Array.prototype.heapify = function (index, heapSize) {
let largest = index
const leftIndex = 2 * index + 1
Expand Down
3 changes: 2 additions & 1 deletion Sorts/selectionSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*In every iteration of selection sort, the minimum element (considering ascending order)
*from the unsorted subarray is picked and moved to the sorted subarray.
*/

function selectionSort (items) {
var length = items.length
for (var i = 0; i < length - 1; i++) {
Expand All @@ -17,7 +18,7 @@ function selectionSort (items) {
min = j // Change the current min number position if a smaller num is found
}
}
if (min != i) {
if (min !== i) {
// After each pass, if the current min num != initial min num, exchange the position.
// Swap the numbers
var tmp = items[i]
Expand Down