Study of computational time of Dijkstra's Algorithm using different data structures

26
Study of computational time of Dijkstra’s Algorithm using different data structures Nirnimesh Ghose (23221752) May 7, 2014

Transcript of Study of computational time of Dijkstra's Algorithm using different data structures

Study of computational time of Dijkstra’sAlgorithm using different data structures

Nirnimesh Ghose (23221752)

May 7, 2014

Contents

1 Introduction 21.1 Dijkstra’s Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.2.1 Array Implementation . . . . . . . . . . . . . . . . . . . . 21.2.2 Dial’s Implementation . . . . . . . . . . . . . . . . . . . . 21.2.3 Binary Heap Implementation . . . . . . . . . . . . . . . . 31.2.4 Fibonacci Heap Implementation . . . . . . . . . . . . . . . 3

1.3 Pseudo Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Implementation 42.1 Array Implementation . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Dial’s Implementation . . . . . . . . . . . . . . . . . . . . . . . . 52.3 Binary Heap Implementation . . . . . . . . . . . . . . . . . . . . 52.4 Fibonacci Heap Implementation . . . . . . . . . . . . . . . . . . . 6

3 Simulation 8

A Code in Java 10A.1 Dijkstra Algorithm Application . . . . . . . . . . . . . . . . . . . 10A.2 Dijkstra Algorithm Array . . . . . . . . . . . . . . . . . . . . . . 12A.3 Dijkstra Algorithm Dial . . . . . . . . . . . . . . . . . . . . . . . 14A.4 Dijkstra Algorithm Binary Heap . . . . . . . . . . . . . . . . . . . 16A.5 Binary Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18A.6 Dijkstra Algorithm Fibonacci Heap . . . . . . . . . . . . . . . . . 20A.7 Fibonacci Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22A.8 Vertex Impl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

1

Chapter 1

Introduction

1.1 Dijkstra’s AlgorithmsDijkstra’s algorithms was proposed by Edsger Dijkstra in 1956. It is used to solvea directed graph with non negative weights of edges for single source shortest path.It calculates path with lowest cost to different vertex in the graph from a singlesource vertex of the graph.

1.2 Data Structures

1.2.1 Array ImplementationArray is used to store the cost to each node. Minimum cost is found out fromthe array in start of each while loop.Running time is O(|E||V|) where |E| = Number of edges and |V| = Number ofvertices.

1.2.2 Dial’s ImplementationDial’s implementation is used to improve the bottleneck condition of selectingthe minimum at the starting of while loop each time.Dial’s implementation usesC+1 buckets to store cost to each vertex where C is the maximum cost of allthe costs between the vertices. It is used such that a bucket k contains all nodehaving cost from source node equal to k. Here k is calculated as the remainderwhen original cost is divided by the maximum cost.Running time is O(|E|+|V|C) where |E| = Number of edges and |V| = Numberof vertices.

2

1.2.3 Binary Heap ImplementationBinary Heap data structure requires O(log n) time to perform find minimum andinsert. So, it can be used to still improve the bottleneck of finding the minimumin the while loop.Running time is O(|E|log|V|) where |E| = Number of edges and |V| = Numberof vertices.

1.2.4 Fibonacci Heap ImplementationFibonacci heap data structure performs insert in O(1) time and find minimum inO(log n) time. Thus it helps to improve the running time of Dijkstra’s algorithm.Running time is O(|E|+|V|log|V|) where |E| = Number of edges and |V| = Num-ber of vertices.

1.3 Pseudo Codebegin

S := φ; S := N ;d(i) := ∞ ∀ N ;d(s) := 0 and pred(s) := 0 where s → source node;while |S| < n dobegin

let i ∈ S be a node for which d(i) = min{d(j) : j ∈ S};S := S∪{i};S = S − {i};for each(i,j)∈ A(i) do

if d(j)≥ d(i) + cij thend(j) := d(i)+cij;pred(j):=i;

end;end;

end;end;

3

Chapter 2

Implementation

Implementation of each data structure is shown using a directed test graph withrandom cost between the vertices. Graph used to show implementation is figure2.1. Source node is 1 and sink node is 6.

Figure 2.1: Test Graph

4

2.1 Array ImplementationW P

1 2 3 4 5 6 1 2 3 4 5 60 ∞ ∞ ∞ ∞ ∞ 0 - - - - -0 1380 1435 ∞ ∞ ∞ 0 1 1 - - -0 1380 1435 1653 2454 ∞ 0 1 1 2 2 -0 1380 1435 1653 2454 ∞ 0 1 1 2 2 -0 1380 1435 1653 1897 2251 0 1 1 2 4 40 1380 1435 1653 1897 1931 0 1 1 2 4 50 1380 1435 1653 1897 1931 0 1 1 2 4 5

Shortest path: 1→ 2→ 4→ 5→ 6Shortest path weight: 1931

2.2 Dial’s ImplementationDial shown in straight line. Each line shows new iteration.

maxWeight = 1683NodeName(Weight mod maxWeight)1(0)2(1380)→ 3(1435)3(1435)→ 4(1653)→ 5(771)4(1653)→ 5(771)5(214)→ 6(559)6(248)

Shortest path: 1→ 2→ 4→ 5→ 6Shortest path weight: 1931

2.3 Binary Heap ImplementationBinary Heap is shown for each iteration.NodeName(Weight)1st Iteration

1(0)

2nd Iteration:1(0)

↙ ↘2(1380) 3(1435)

5

3rd Iteration:2(1380)

↙ ↘3(1435) 4(1653)↙

5(2454)4th Iteration:

3(1435)↙ ↘

5(2454) 4(1653)5th Iteration:

4(1653)↙ ↘

5(1897) 6(2242)6th Iteration:

5(1897)↙

6(1931)7th Iteration:

6(1931)

2.4 Fibonacci Heap ImplementationFibonacci Heap is shown for each iteration.NodeName(Weight)1st Iteration

1(0)

2nd Iteration:2(1380)

↙3(1435)

3rd Iteration:3(1435)

↙ ↘5(2454) 4(1653)

4th Iteration:

6

4(1653)↙ ↘

5(1897) 6(2242)5th Iteration:

5(1897)↙

6(1931)6th Iteration:

6(1931)

7

Chapter 3

Simulation

Simulation is done on java 1.6 on a machine with Intel(R) Core(TM) i7-3610QMCPU @ 2.30GHz processor and 8.00 GB RAM. Number of nodes in the directedgraph is increased from 4 to 3000 with increment of 4 nodes in each iteration.Input matrix is the adjacency matrix. The weights for the edges are chosen atrandom between 1 and 2000. Running time is noted for each implementation innano second.The simulation results are as expected with array implementation taking themaximum time followed by binary heap implementation then dial’s implemen-tation and the fastest being Fibonacci heap implementation. The computationtime difference is visually more visible with increasing the number of nodes, itsmore clearly visible after 1200 nodes.Simulation results are plotted with computational time in nano second againstthe number of nodes in the graph. Results can be seen in figure: 3.1.

8

Figure 3.1: Computational Time of Various implementation

9

Appendix A

Code in Java

A.1 Dijkstra Algorithm Applicationpackage sie.hw.five.dijkstraalgorithm;

import java.io.FileNotFoundException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.util.Random;

public class DijkstraAlgorithmApplication{public static void main(String [] args){long startTime = 0;long endTime = 0;long totalTime = 0;DijkstraAlgorithmArray daa = new DijkstraAlgorithmArray ();DijkstraAlgorithmDial dad = new DijkstraAlgorithmDial ();DijkstraAlgorithmBinaryHeap dab = new DijkstraAlgorithmBinaryHeap ();DijkstraAlgorithmFibonacciHeap daf = new DijkstraAlgorithmFibonacciHeap ();try {PrintWriter writerArray = new PrintWriter("C:/Users/nirnimesh/Documents/Classes␣

at␣UA/Spring␣2014/ SIE546/Project/output/array1.txt", "UTF -8");PrintWriter writerDial = new PrintWriter("C:/Users/nirnimesh/Documents/Classes␣

at␣UA/Spring␣2014/ SIE546/Project/output/dial1.txt", "UTF -8");PrintWriter writerBinary = new PrintWriter("C:/Users/nirnimesh/Documents/Classes

␣at␣UA/Spring␣2014/ SIE546/Project/output/binary1.txt", "UTF -8");PrintWriter writerFibo = new PrintWriter("C:/Users/nirnimesh/Documents/Classes␣

at␣UA/Spring␣2014/ SIE546/Project/output/fibo1.txt", "UTF -8");try {System.out.println("Started");for(int number_of_nodes =4; number_of_nodes <=3000; number_of_nodes +=4){long [][] graph_matrix = getGraph(number_of_nodes);int number_of_iterations = 1;totalTime = 0;for(int i=0;i<number_of_iterations;i++){startTime = System.nanoTime ();dad.execute(graph_matrix , number_of_nodes);endTime = System.nanoTime ();totalTime += (endTime -startTime);}writerDial.println(number_of_nodes+"\t"+ (totalTime/number_of_iterations) + "␣ns

");totalTime = 0;for(int i=0;i<number_of_iterations;i++){startTime = System.nanoTime ();

10

dab.execute(graph_matrix , number_of_nodes);endTime = System.nanoTime ();totalTime += (endTime -startTime);}writerBinary.println(number_of_nodes+"\t"+ (totalTime/number_of_iterations) + "␣

ns");totalTime = 0;for(int i=0;i<number_of_iterations;i++){startTime = System.nanoTime ();daf.execute(graph_matrix , number_of_nodes);endTime = System.nanoTime ();totalTime += (endTime -startTime);}writerFibo.println(number_of_nodes+"\t"+ (totalTime/number_of_iterations) + "␣ns

");totalTime = 0;for(int i=0;i<number_of_iterations;i++){startTime = System.nanoTime ();daa.execute(graph_matrix , number_of_nodes);endTime = System.nanoTime ();totalTime += (endTime -startTime);}writerArray.println(number_of_nodes+"\t"+ (totalTime/number_of_iterations) + "␣

ns");}}catch (Exception e) {writerDial.close ();writerBinary.close();writerFibo.close ();writerArray.close();e.printStackTrace ();}writerDial.close ();writerBinary.close();writerFibo.close ();writerArray.close();} catch (FileNotFoundException e) {e.printStackTrace ();} catch (UnsupportedEncodingException e) {e.printStackTrace ();}System.out.println("Done !!!!");}public static long [][] getGraph(int number_of_nodes){long graph_matrix [][] = new long [(int) (number_of_nodes + 1)][( int) (

number_of_nodes + 1)];long x = 1L;long y = 2000L;Random r = new Random ();if (number_of_nodes >= 4){for (long i = 0; i < number_of_nodes; i++){if (i == 1 || i == 2){graph_matrix [1][( int) (i + 1)] = x+(( long)(r.nextDouble ()*(y-x)));}else{graph_matrix [1][( int) (i + 1)] = 0;}}for (long i = 1; i < number_of_nodes; i++){for (long j = 0; j < number_of_nodes; j++){if (i % 2 == 1){if (j == i + 1 || j == i + 2 || j == i + 3){graph_matrix [(int) (i + 1)][( int) (j + 1)] = x+(( long)(r.nextDouble ()*(y-x)));}else{graph_matrix [(int) (i + 1)][( int) (j + 1)] = 0;}}else{if (j == i + 1){graph_matrix [(int) (i + 1)][( int) (j + 1)] = x+(( long)(r.nextDouble ()*(y-x)));} else{graph_matrix [(int) (i + 1)][( int) (j + 1)] = 0;}}}}}return graph_matrix ;}}

11

A.2 Dijkstra Algorithm Arraypackage sie.hw.five.dijkstraalgorithm;

import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;import java.util.Map;

public class DijkstraAlgorithmArray{private final long INFINITY = 1000000L;public void execute(long [][] graph , long nodes){Map <String , VertexImpl > unmarkedListBucket = new HashMap <String , VertexImpl >();Map <String , VertexImpl > markedMap = new HashMap <String , VertexImpl >();VertexImpl [] costListArray = new VertexImpl [6000];for(int i = 1; i<=nodes; i++){VertexImpl v = new VertexImpl ();v.setName(Long.toString(i));v.setWeight(INFINITY);v.setPred(null);unmarkedListBucket.put(Long.toString(i), v);}VertexImpl source = new VertexImpl ();source.setName("1");source.setWeight (0);source.setPred(null);costListArray [0] = source;int current = 1;unmarkedListBucket.get(Long.toString (1)).setWeight (0);while (! unmarkedListBucket.isEmpty ()){Arrays.sort(costListArray , new Comparator <VertexImpl >(){@Overridepublic int compare(VertexImpl o1 , VertexImpl o2){if(o1!= null && o2!= null){long comparedWeight = o2.getWeight ();if(o1.getWeight () > comparedWeight){return 1;}else if (o1.getWeight () == comparedWeight){return 0;}else{return -1; }}else{return 0;}}});VertexImpl node = new VertexImpl ();node.setName(costListArray [0]. getName ());node.setPred(costListArray [0]. getPred ());node.setWeight(costListArray [0]. getWeight ());costListArray [0]. setWeight(INFINITY);unmarkedListBucket.remove(node.getName ());markedMap.put(node.getName (),node);for(int i=1; i<=nodes; i++){if(graph[(int) Long.parseLong(node.getName ())][i]!=0){if(unmarkedListBucket.get(Long.toString(i))!= null){if(unmarkedListBucket.get(Long.toString(i)).getWeight ()>graph[(int) Long.

parseLong(node.getName ())][i]+node.getWeight ()){unmarkedListBucket.get(Long.toString(i)).setWeight(graph [(int) Long.parseLong(

node.getName ())][i]+node.getWeight ());unmarkedListBucket.get(Long.toString(i)).setPred(node.getName ());boolean check = false;int k = 0;while(costListArray[k] != null){if (costListArray[k]. getName ().equalsIgnoreCase(Long.toString(i))){costListArray[k]

12

.setWeight(unmarkedListBucket.get(Long.toString(i)).getWeight ());costListArray[k]. setPred(unmarkedListBucket.get(Long.toString(i)).getPred ());check = true ;}k++;}if(!check){costListArray[current ]=( unmarkedListBucket.get(Long.toString(i)));current ++;}}}}}}System.out.println ();System.out.println("Final␣Weights:␣");System.out.println("NodeName\tWeight\tPredecessor");for(int i=1; i<=nodes;i++){System.out.println(markedMap.get(Long.toString(i)).getName ()+"\t\t"+markedMap.get(Long.toString(i)).getWeight ()+"\t"+markedMap.get(Long.toString(i))

.getPred ());}VertexImpl vertex = markedMap.get(Long.toString(nodes));String path = vertex.getName ();int pathValue = (int) vertex.getWeight ();do{vertex = markedMap.get(vertex.getPred ());path += "->"+vertex.getName ();}while (! vertex.getName ().equalsIgnoreCase("1"));System.out.println ();System.out.println("Shortest␣Path␣From␣Sink␣to␣Source:");System.out.println(path);System.out.println("Shortest␣From␣Sink␣to␣Source:␣"+pathValue);}}

13

A.3 Dijkstra Algorithm Dialpackage sie.hw.five.dijkstraalgorithm;

import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;

public class DijkstraAlgorithmDial{private final long INFINITY = 1000000L;public void execute(long [][] graph , long nodes){Map <String , VertexImpl > unmarkedListBucket = new HashMap <String , VertexImpl >();Map <String , VertexImpl > markedMap = new HashMap <String , VertexImpl >();List <LinkedList <VertexImpl >> bucketOfList = new ArrayList <LinkedList <VertexImpl

>>();LinkedList <VertexImpl > costListOne = new LinkedList <VertexImpl >();long max = getMax(graph , nodes);boolean added = false;for(int i = 1; i<=nodes; i++){VertexImpl v = new VertexImpl ();v.setName(Long.toString(i));v.setWeight(INFINITY);v.setPred(null);unmarkedListBucket.put(Long.toString(i), v);}VertexImpl source = new VertexImpl ();source.setName("1");source.setWeight (0);source.setPred(null);costListOne.add(source);unmarkedListBucket.get(Long.toString (1)).setWeight (0);System.out.println(max);bucketOfList.add(costListOne);while (! unmarkedListBucket.isEmpty ()){LinkedList <VertexImpl > costList = bucketOfList.get(0);Collections.sort(costList);for(LinkedList <VertexImpl > costListout:bucketOfList){for(VertexImpl cost:costListout){System.out.print(cost.getName ()+"("+cost.getWeight ()+")"+"->");}}System.out.println ();VertexImpl costNode = costList.get(0);costList.remove(costNode);if(costList.isEmpty () && added){bucketOfList.remove(costList);}VertexImpl node;if (unmarkedListBucket.get(costNode.getName ()) != null){node = unmarkedListBucket.get(costNode.getName ());unmarkedListBucket.remove(node.getName ());markedMap.put(node.getName (), node);for(int i=1; i<=nodes; i++){if(graph[(int) Long.parseLong(node.getName ())][i]!=0){if(unmarkedListBucket.get(Long.toString(i))!= null){if(unmarkedListBucket.get(Long.toString(i)).getWeight ()>graph[(int) Long.

parseLong(node.getName ())][i]+node.getWeight ()){unmarkedListBucket.get(Long.toString(i)).setWeight(graph [(int) Long.parseLong(

node.getName ())][i]+node.getWeight ());unmarkedListBucket.get(Long.toString(i)).setPred(node.getName ());boolean check = false;for(VertexImpl cost:costList){if(cost.getName ().equalsIgnoreCase(Long.toString(i))){long weight = unmarkedListBucket.get(Long.toString(i)).getWeight ();cost.setWeight(weight%max);

14

cost.setPred(unmarkedListBucket.get(Long.toString(i)).getPred ());check = true ;}}if(!check){VertexImpl newNode = new VertexImpl ();newNode.setName(unmarkedListBucket.get(Long.toString(i)).getName ());newNode.setPred(unmarkedListBucket.get(Long.toString(i)).getPred ());long weight = unmarkedListBucket.get(Long.toString(i)).getWeight ();newNode.setWeight(weight%max);if(unmarkedListBucket.get(Long.toString(i)).getWeight ()<max){bucketOfList.get(0).add(newNode);}else{LinkedList <VertexImpl > costListNext = new LinkedList <VertexImpl >();costListNext.add(newNode);bucketOfList.add(costListNext);added = true ;}}}}}}}}System.out.println ();System.out.println("Final␣Weights:␣");System.out.println("NodeName\tWeight\tPredecessor");for(int i=1; i<=nodes;i++){System.out.println(markedMap.get(Long.toString(i)).getName ()+"\t\t"+markedMap.get(Long.toString(i)).getWeight ()+"\t"+markedMap.get(Long.toString(i))

.getPred ());}VertexImpl vertex = markedMap.get(Long.toString(nodes));String path = vertex.getName ();int pathValue = (int) vertex.getWeight ();do{vertex = markedMap.get(vertex.getPred ());path += "->"+vertex.getName ();}while (! vertex.getName ().equalsIgnoreCase("1"));System.out.println ();System.out.println("Shortest␣Path␣From␣Sink␣to␣Source:");System.out.println(path);System.out.println("Shortest␣From␣Sink␣to␣Source:␣"+pathValue);}public long getMax(long [][] graph , long number){long max = Long.MIN_VALUE;for(long i=0; i<number; i ++){for(long j=0;j<number;j++){if(max <graph [(int) i+1][( int) j+1]){max = graph [(int) i+1][( int) j+1];}}}return max ;}}

15

A.4 Dijkstra Algorithm Binary Heappackage sie.hw.five.dijkstraalgorithm;

import java.util.HashMap;import java.util.Map;

public class DijkstraAlgorithmBinaryHeap{private final long INFINITY = 1000000L;public void execute(long [][] graph , long nodes){Map <String , VertexImpl > unmarkedListBucket = new HashMap <String , VertexImpl >();Map <String , VertexImpl > markedMap = new HashMap <String , VertexImpl >();VertexImpl [] costListArray = new VertexImpl [6000];BinaryHeap <VertexImpl > costHeap = new BinaryHeap <VertexImpl >( costListArray);for(int i = 1; i<=nodes; i++){VertexImpl v = new VertexImpl ();v.setName(Long.toString(i));v.setWeight(INFINITY);v.setPred(null);unmarkedListBucket.put(Long.toString(i), v);}VertexImpl source = new VertexImpl ();source.setName("1");source.setWeight (0);source.setPred(null);costHeap.add(source);unmarkedListBucket.get(Long.toString (1)).setWeight (0);while (! unmarkedListBucket.isEmpty ()){VertexImpl node = costHeap.remove ();System.out.println(node.getName ()+"("+node.getWeight ()+")");unmarkedListBucket.remove(node.getName ());markedMap.put(node.getName (),node);for(int i=1; i<=nodes; i++){if(graph[(int) Long.parseLong(node.getName ())][i]!=0){if(unmarkedListBucket.get(Long.toString(i))!= null){if(unmarkedListBucket.get(Long.toString(i)).getWeight ()>graph[(int) Long.

parseLong(node.getName ())][i]+node.getWeight ()){unmarkedListBucket.get(Long.toString(i)).setWeight(graph [(int) Long.parseLong(

node.getName ())][i]+node.getWeight ());unmarkedListBucket.get(Long.toString(i)).setPred(node.getName ());boolean check = false;VertexImpl [] array = costHeap.getArray ();int k = 0;while(array[k] != null){if (array[k]. getName ().equalsIgnoreCase(Long.toString(i))){array[k].setWeight(unmarkedListBucket.get(Long.toString(i)).getWeight ());array[k]. setPred(unmarkedListBucket.get(Long.toString(i)).getPred ());check = true ;}k++;}

if(!check){costHeap.add(unmarkedListBucket.get(Long.toString(i)));}else{costHeap.setArray(array);}}}}}}System.out.println ();System.out.println("Final␣Weights:␣");System.out.println("NodeName\tWeight\tPredecessor");for(int i=1; i<=nodes;i++){System.out.println(markedMap.get(Long.toString(i)).getName ()+"\t\t"+

16

markedMap.get(Long.toString(i)).getWeight ()+"\t"+markedMap.get(Long.toString(i)).getPred ());}

VertexImpl vertex = markedMap.get(Long.toString(nodes));String path = vertex.getName ();int pathValue = (int) vertex.getWeight ();do{vertex = markedMap.get(vertex.getPred ());path += "->"+vertex.getName ();}while (! vertex.getName ().equalsIgnoreCase("1"));System.out.println ();System.out.println("Shortest␣Path␣From␣Sink␣to␣Source:");System.out.println(path);System.out.println("Shortest␣From␣Sink␣to␣Source:␣"+pathValue);}}

17

A.5 Binary Heappackage sie.hw.five.dijkstraalgorithm;

import java.util.Arrays;

public class BinaryHeap <T extends Comparable <T>>{protected T[] array;protected int size;public BinaryHeap (T[] array){this.array = array;size = 0;}public T[] getArray (){return (T[]) array; }public void setArray(T[] array){this.array = array;bubbleUp ();}public void add(T value){if (size >= array.length - 1){array = this.resize ();}size ++;int index = size;array[index] = value;bubbleUp ();}public boolean isEmpty (){return size == 0;}public T peek(){if (this.isEmpty ()){throw new IllegalStateException ();}return array [1];}public T remove (){T result = peek();array [1] = array[size];array[size] = null;size --;bubbleDown ();return result ;}

public String toString (){return Arrays.toString(array);}

protected void bubbleDown (){int index = 1;while (hasLeftChild(index)){int smallerChild = leftIndex(index);if (hasRightChild(index)&& array[leftIndex(index)]. compareTo(array[rightIndex(index)]) > 0){smallerChild = rightIndex(index);}if (array[index]. compareTo(array[smallerChild ]) > 0){swap(index , smallerChild);}else{break ;}index = smallerChild ;}}protected void bubbleUp (){int index = this.size;while (hasParent(index)&& (parent(index).compareTo(array[index]) > 0)) {swap(index , parentIndex(index));index = parentIndex(index);}}protected boolean hasParent(int i){return i > 1;}protected int leftIndex(int i){return i * 2;}protected int rightIndex(int i)

18

{return i * 2 + 1;}protected boolean hasLeftChild(int i){return leftIndex(i) <= size;}protected boolean hasRightChild(int i){return rightIndex(i) <= size;}protected T parent(int i) {return array[parentIndex(i)];}protected int parentIndex(int i){return i / 2;}protected T[] resize (){return Arrays.copyOf(array , array.length * 2);}protected void swap(int index1 , int index2){T tmp = array[index1 ];array[index1] = array[index2 ];array[index2] = tmp ;}}

19

A.6 Dijkstra Algorithm Fibonacci Heappackage sie.hw.five.dijkstraalgorithm;

import java.util.HashMap;import java.util.Map;

public class DijkstraAlgorithmFibonacciHeap{private final long INFINITY = 1000000L;public void execute(long [][] graph , long nodes){Map <String , VertexImpl > unmarkedListBucket = new HashMap <String , VertexImpl >();Map <String , VertexImpl > markedMap = new HashMap <String , VertexImpl >();FibonacciHeap <VertexImpl > costHeap = new FibonacciHeap <VertexImpl >();for(int i = 1; i<=nodes; i++){VertexImpl v = new VertexImpl ();v.setName(Long.toString(i));v.setWeight(INFINITY);v.setPred(null);unmarkedListBucket.put(Long.toString(i), v);}VertexImpl source = new VertexImpl ();source.setName("1");source.setWeight (0);source.setPred(null);costHeap.enqueue(source , source.getWeight ());unmarkedListBucket.get(Long.toString (1)).setWeight (0);while (! unmarkedListBucket.isEmpty ()){VertexImpl node = costHeap.dequeueMin ().getValue ();unmarkedListBucket.remove(node.getName ());markedMap.put(node.getName (),node);for(int i=1; i<=nodes; i++){if(graph[(int) Long.parseLong(node.getName ())][i]!=0){if(unmarkedListBucket.get(Long.toString(i))!= null){if(unmarkedListBucket.get(Long.toString(i)).getWeight ()>graph[(int) Long.

parseLong(node.getName ())][i]+node.getWeight ()){unmarkedListBucket.get(Long.toString(i)).setWeight(graph [(int) Long.parseLong(

node.getName ())][i]+node.getWeight ());unmarkedListBucket.get(Long.toString(i)).setPred(node.getName ());boolean check = false;FibonacciHeap <VertexImpl > tempCostHeap = new FibonacciHeap <VertexImpl >();while (! costHeap.isEmpty ()){FibonacciHeap.Entry <VertexImpl > temp = costHeap.dequeueMin ();if(temp.getValue ().getName ().equalsIgnoreCase(Long.toString(i))){temp.getValue ().setWeight(unmarkedListBucket.get(Long.toString(i)).getWeight ());temp.getValue ().setPred(unmarkedListBucket.get(Long.toString(i)).getPred ());check = true ;}tempCostHeap.enqueue(temp.getValue (), temp.getValue ().getWeight ());}if(!check){tempCostHeap.enqueue(unmarkedListBucket.get(Long.toString(i)),

unmarkedListBucket.get(Long.toString(i)).getWeight ());}costHeap = tempCostHeap ;}}}}}System.out.println ();System.out.println("Final␣Weights:␣");System.out.println("NodeName\tWeight\tPredecessor");for(int i=1; i<=nodes;i++){System.out.println(markedMap.get(Long.toString(i)).getName ()+"\t\t"+markedMap.get(Long.toString(i)).getWeight ()+"\t"+markedMap.get(Long.toString(i))

.getPred ());}VertexImpl vertex = markedMap.get(Long.toString(nodes));String path = vertex.getName ();int pathValue = (int) vertex.getWeight ();do

20

{vertex = markedMap.get(vertex.getPred ());path += "->"+vertex.getName ();}while (! vertex.getName ().equalsIgnoreCase("1"));System.out.println ();System.out.println("Shortest␣Path␣From␣Sink␣to␣Source:");System.out.println(path);System.out.println("Shortest␣From␣Sink␣to␣Source:␣"+pathValue);}}

21

A.7 Fibonacci Heappackage sie.hw.five.dijkstraalgorithm;

import java.util.ArrayList;import java.util.List;import java.util.NoSuchElementException;

public final class FibonacciHeap <T>{public static final class Entry <T>{private int mDegree = 0;private boolean mIsMarked = false;private Entry <T> mNext;private Entry <T> mPrev;private Entry <T> mParent;private Entry <T> mChild;private T mElem;private double mPriority;public T getValue (){return mElem;}public void setValue(T value){mElem = value;}public double getPriority (){return mPriority ;}private Entry(T elem , double priority){mNext = mPrev = this;mElem = elem;mPriority = priority ;}}private Entry <T> mMin = null;private int mSize = 0;public Entry <T> enqueue(T value , double priority){checkPriority(priority);Entry <T> result = new Entry <T>(value , priority);mMin = mergeLists(mMin , result);++mSize;return result ;}public Entry <T> min(){if (isEmpty ())throw new NoSuchElementException("Heap␣is␣empty.");return mMin;}public boolean isEmpty (){return mMin == null ;}public int size(){return mSize;}public static <T> FibonacciHeap <T> merge(FibonacciHeap <T> one , FibonacciHeap <T>

two){FibonacciHeap <T> result = new FibonacciHeap <T>();result.mMin = mergeLists(one.mMin , two.mMin);result.mSize = one.mSize + two.mSize;one.mSize = two.mSize = 0;one.mMin = null;two.mMin = null;return result ;}public Entry <T> dequeueMin (){if (isEmpty ())throw new NoSuchElementException("Heap␣is␣empty.");--mSize;Entry <T> minElem = mMin;if (mMin.mNext == mMin){mMin = null ;}else {mMin.mPrev.mNext = mMin.mNext;mMin.mNext.mPrev = mMin.mPrev;mMin = mMin.mNext; }if (minElem.mChild != null)

22

{Entry <?> curr = minElem.mChild;do {curr.mParent = null;curr = curr.mNext;} while (curr != minElem.mChild);}mMin = mergeLists(mMin , minElem.mChild);if (mMin == null) return minElem;List <Entry <T>> treeTable = new ArrayList <Entry <T>>();List <Entry <T>> toVisit = new ArrayList <Entry <T>>();for (Entry <T> curr = mMin; toVisit.isEmpty () || toVisit.get (0) != curr; curr =

curr.mNext)toVisit.add(curr);for (Entry <T> curr: toVisit) {while (true) {while (curr.mDegree >= treeTable.size())treeTable.add(null);if (treeTable.get(curr.mDegree) == null) {treeTable.set(curr.mDegree , curr);break ;}Entry <T> other = treeTable.get(curr.mDegree);treeTable.set(curr.mDegree , null);Entry <T> min = (other.mPriority < curr.mPriority)? other : curr;Entry <T> max = (other.mPriority < curr.mPriority)? curr : other;max.mNext.mPrev = max.mPrev;max.mPrev.mNext = max.mNext;max.mNext = max.mPrev = max;min.mChild = mergeLists(min.mChild , max);max.mParent = min;max.mIsMarked = false;++min.mDegree;curr = min;}if (curr.mPriority <= mMin.mPriority) mMin = curr;}return minElem ;}public void decreaseKey(Entry <T> entry , double newPriority) {checkPriority(newPriority);if (newPriority > entry.mPriority)throw new IllegalArgumentException("New␣priority␣exceeds␣old.");decreaseKeyUnchecked(entry , newPriority);}public void delete(Entry <T> entry) {decreaseKeyUnchecked(entry , Double.NEGATIVE_INFINITY);dequeueMin ();}private void checkPriority(double priority) {if (Double.isNaN(priority))throw new IllegalArgumentException(priority + "␣is␣invalid.");}private static <T> Entry <T> mergeLists(Entry <T> one , Entry <T> two) {if (one == null && two == null) {return null ;}else if (one != null && two == null) {return one;}else if (one == null && two != null) {return two;}else {Entry <T> oneNext = one.mNext;one.mNext = two.mNext;one.mNext.mPrev = one;two.mNext = oneNext;two.mNext.mPrev = two;return one.mPriority < two.mPriority? one : two ;}}private void decreaseKeyUnchecked(Entry <T> entry , double priority) {entry.mPriority = priority;if (entry.mParent != null && entry.mPriority <= entry.mParent.mPriority)cutNode(entry);if (entry.mPriority <= mMin.mPriority)mMin = entry;}private void cutNode(Entry <T> entry) {entry.mIsMarked = false;

23

if (entry.mParent == null) return;if (entry.mNext != entry) {entry.mNext.mPrev = entry.mPrev;entry.mPrev.mNext = entry.mNext;}if (entry.mParent.mChild == entry) {if (entry.mNext != entry) {entry.mParent.mChild = entry.mNext;}else {entry.mParent.mChild = null ;}}--entry.mParent.mDegree;entry.mPrev = entry.mNext = entry;mMin = mergeLists(mMin , entry);if (entry.mParent.mIsMarked)cutNode(entry.mParent);elseentry.mParent.mIsMarked = true;entry.mParent = null ;}}

24

A.8 Vertex Implpackage sie.hw.five.dijkstraalgorithm;

public class VertexImpl implements Comparable <VertexImpl >{private String name;private String pred;private long weight;public VertexImpl (){super ();}public String getName (){return name;}public void setName(String name){this.name = name;}public String getPred (){return pred;}public void setPred(String pred){this.pred = pred;}public long getWeight (){return weight ;}public void setWeight(long weight){this.weight = weight ;}@Overridepublic int compareTo(VertexImpl arg0){long comparedWeight = arg0.weight;if(this.weight > comparedWeight){return 1;}else if (this.weight == comparedWeight){return 0;}else{return -1; }}}

25