Skip to content
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

Feature- Adding merge sort #8

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 0 additions & 6 deletions .idea/encodings.xml

This file was deleted.

3 changes: 2 additions & 1 deletion .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 1 addition & 17 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,7 @@ dependencies {
}


testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'

}
10 changes: 10 additions & 0 deletions app/src/main/assets/desc.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,16 @@
"<a href='https://github.com/naman14/AlgorithmVisualizer-Android/blob/master/app/src/main/java/com/naman14/algovisualizer/visualizer/SortingVisualizer.java'>SortingVisualizer</a>"
]
},
"merge_sort": {
"Merge Sort": "Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves",
"Complexity": {
"Time": "worst O(n log(n)), best O(n log(n)), average O(n log(n))",
"Space": "worst O(n) auxiliary"
},
"References": [
"<a href='https://en.wikipedia.org/wiki/Merge_sort'>Wikipedia<a/><br>"
]
},
"linked_list": {
"Singly linked list": "A Linked List is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. ",
"Complexity": {
Expand Down
36 changes: 36 additions & 0 deletions app/src/main/java/com/naman14/algovisualizer/AlgorithmCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,42 @@ public class AlgorithmCode {
" addLog(\"Array has been sorted\");\n" +
" completed();";

public static final String CODE_MERGE_SORT = "" +
"public void mergeSort(int start, int end){\n" +
" if (start >= end){\n" +
" return;\n" +
" }\n" +
" int middle = (start + end)/2;\n" +
" mergeSort(start,middle);\n" +
" mergeSort(middle+1,end);\n" +
" merge(start,middle,middle+1,end);\n" +
"}\n" +
"public void merge(int start1, int end1, int start2, int end2){\n" +
" List<Integer> sortedList = new ArrayList<Integer>();\n" +
" List<Integer> indexes = new ArrayList<Integer>();\n" +
" int s0 = start1;\n" +
" while(start1 <= end1){\n" +
" if (start2 > end2){\n" +
" sortedList.add(array[start1]);\n" +
" start1+=1;\n" +
" continue;\n" +
" }\n" +
" if (array[start1] <= array[start2]){\n" +
" sortedList.add(array[start1]);\n" +
" start1+=1;\n" +
" }\n" +
" else{\n" +
" sortedList.add(array[start2]);\n" +
" start2+=1;\n" +
" }\n" +
" }\n" +
" int i = 0;\n" +
" for (int number:sortedList) {\n" +
" array[s0+i]=number;\n" +
" i+=1;\n" +
" }\n" +
"}";

public static final String CODE_BST_SEARCH = " int id = DataUtils.getRandomKeyFromBST();\n" +
" addLog(\"Searching for \" + String.valueOf(id));\n" +
" BinarySearchTree.Node current = b.getRoot();\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ public void setCode(String key) {
case Algorithm.SELECTION_SORT:
addCodeItem(AlgorithmCode.CODE_SELECTION_SORT,"Selection sort");
break;
case Algorithm.MERGE_SORT:
addCodeItem(AlgorithmCode.CODE_MERGE_SORT, "Merge sort");
break;
case Algorithm.BST_SEARCH:
addCodeItem(AlgorithmCode.CODE_BST_SEARCH, "BST Search");
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ public boolean onChildClick(ExpandableListView expandableListView, View view, in
break;
case 2:
algoFragment.setupFragment(Algorithm.SELECTION_SORT);
break;
case 3:
algoFragment.setupFragment(Algorithm.MERGE_SORT);
break;
}
break;
case 2:
Expand Down Expand Up @@ -208,6 +212,7 @@ private void prepareListData() {
heading2.add("Bubble Sort");
heading2.add("Insertion Sort");
heading2.add("Selection Sort");
heading2.add("Merge Sort");
List<String> heading3 = new ArrayList<String>();
heading3.add("BST Search");
heading3.add("BST Insert");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import com.naman14.algovisualizer.algorithm.search.LinearSearch;
import com.naman14.algovisualizer.algorithm.sorting.BubbleSort;
import com.naman14.algovisualizer.algorithm.sorting.InsertionSort;
import com.naman14.algovisualizer.algorithm.sorting.MergeSort;
import com.naman14.algovisualizer.algorithm.sorting.SelectionSort;
import com.naman14.algovisualizer.algorithm.tree.bst.BSTAlgorithm;
import com.naman14.algovisualizer.visualizer.AlgorithmVisualizer;
Expand Down Expand Up @@ -190,6 +191,12 @@ public void setupFragment(String algorithmKey) {
algorithm = new SelectionSort((SortingVisualizer) visualizer, getActivity(), logFragment);
((SelectionSort) algorithm).setData(DataUtils.createRandomArray(15));
break;
case Algorithm.MERGE_SORT:
visualizer = new SortingVisualizer(getActivity());
appBarLayout.addView(visualizer);
algorithm = new MergeSort((SortingVisualizer)visualizer, getActivity(), logFragment);
((MergeSort)algorithm).setData(DataUtils.createRandomArray(15));
break;
case Algorithm.BST_SEARCH:
visualizer = new BSTVisualizer(getActivity());
appBarLayout.addView(visualizer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class Algorithm extends HandlerThread {
public static final String DFS = "dfs";
public static final String DIJKSTRA = "dijkstra";
public static final String BELLMAN_FORD = "bellman_ford";
public static final String MERGE_SORT = "merge_sort";


public LogFragment logFragment;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.naman14.algovisualizer.algorithm.sorting;

import android.app.Activity;

import com.naman14.algovisualizer.LogFragment;
import com.naman14.algovisualizer.algorithm.Algorithm;
import com.naman14.algovisualizer.algorithm.DataHandler;
import com.naman14.algovisualizer.visualizer.SortingVisualizer;

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

/**
* Created by sergio on 02/01/17.
*/

public class MergeSort extends SortAlgorithm implements DataHandler {

private int[] array;

public MergeSort(SortingVisualizer visualizer, Activity activity, LogFragment logFragment) {
this.visualizer = visualizer;
this.activity = activity;
this.logFragment = logFragment;
}

private void sort(){
logArray("Original array - " ,array);
mergeSort(0,array.length-1);
completed();
}

public void mergeSort(int start, int end){
addLog("Sorting array between " + start + " and " + end);
if (start >= end){
return;
}
int middle = (start + end)/2;
highlightInterval(start,middle);
sleep();
mergeSort(start,middle);
highlightInterval(middle+1,end);
sleep();
mergeSort(middle+1,end);
highlightInterval(start,end);
sleep();
merge(start,middle,middle+1,end);
}

public void merge(int start1, int end1, int start2, int end2){
addLog("merging sub-array " + start1 + " to " + end1 + " and subarray " + start2 + " to " +
end2);
List<Integer> sortedList = new ArrayList<Integer>();
int s0 = start1;
while(start1 <= end1){
if (start2 > end2){
sortedList.add(array[start1]);
start1+=1;
continue;
}
if (array[start1] <= array[start2]){
sortedList.add(array[start1]);
start1+=1;
}
else{
sortedList.add(array[start2]);
start2+=1;
}
}
int i = 0;
for (int number:sortedList) {
array[s0+i]=number;
i+=1;
}
sleep();
}

@Override
public void run() {
super.run();
}

@Override
public void onDataRecieved(Object data) {
super.onDataRecieved(data);
this.array = (int[])data;

}

@Override
public void onMessageReceived(String message) {
super.onMessageReceived(message);
if(message.equals(Algorithm.COMMAND_START_ALGORITHM)){
startExecution();
sort();
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,24 @@ public void run() {
});
}

public void highlightInterval(final int start, final int end){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
visualizer.highlightInterval(start,end);
}
});
}

public void resetInterval(){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
visualizer.highlightInterval(-1,-1);
}
});
}

@Override
public void onDataRecieved(Object data) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public class SortingVisualizer extends AlgorithmVisualizer {
int highlightPositionOne = -1, highlightPositionTwo = -1;
int highlightPosition = -1;
int lineStrokeWidth = getDimensionInPixel(10);
int startInterval, endInterval = -1;


public SortingVisualizer(Context context) {
super(context);
Expand Down Expand Up @@ -72,14 +74,23 @@ protected void onDraw(Canvas canvas) {
for (int i = 0; i < array.length; i++) {

if (i == highlightPositionOne || i == highlightPositionTwo) {
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()), xPos, getHeight(), highlightPaintSwap);
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()),
xPos, getHeight(), highlightPaintSwap);
} else if (i == highlightPosition)
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()), xPos, getHeight(), highlightPaintTrace);
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()),
xPos, getHeight(), highlightPaintTrace);
else if (startInterval >= 0 && endInterval >= startInterval &&
i >= startInterval && i <= endInterval) {
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()),
xPos, getHeight(), highlightPaintTrace);
}
else {
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()), xPos, getHeight(), paint);
canvas.drawLine(xPos, getHeight() - (float) ((array[i] / 10.0) * getHeight()),
xPos, getHeight(), paint);
}

canvas.drawText(String.valueOf(array[i]), xPos - lineStrokeWidth / 3, getHeight() - (float) ((array[i] / 10.0) * getHeight()) - 30, textPaint);
canvas.drawText(String.valueOf(array[i]), xPos - lineStrokeWidth / 3,
getHeight() - (float) ((array[i] / 10.0) * getHeight()) - 30, textPaint);

xPos += margin + 30;
}
Expand Down Expand Up @@ -111,11 +122,23 @@ public void highlightTrace(int position) {
invalidate();
}

public void highlightInterval(int start, int end){
this.startInterval = start;
this.endInterval = end;
invalidate();
}

public void resetHighlightInterval(){
highlightInterval(-1,-1);
}

@Override
public void onCompleted() {
this.highlightPosition = -1;
this.highlightPositionTwo = -1;
this.highlightPositionOne = -1;
this.startInterval = -1;
this.endInterval = -1;
invalidate();
}
}
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
<string name="app_name">AlgorithmVisualizer</string>
<string name="action_settings">Settings</string>
<string name="report_bugs">Report any bugs <u> here </u></string>
<string name="fabric_api_key">key</string>
<string name="play_billing_license_key">key</string>
</resources>
Loading