Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active December 7, 2017 18:31
Show Gist options
  • Save Audhil/92d8e59cf2d9059501e486407314071d to your computer and use it in GitHub Desktop.
Save Audhil/92d8e59cf2d9059501e486407314071d to your computer and use it in GitHub Desktop.
Attempt to learn algorithms in a month
import java.util.Arrays;
// tutorial @ https://www.youtube.com/watch?v=JUOyKSZScW0&index=2&list=PLGLfVvz_LVvReUrWr94U-ZMgjYTQ538nT (bubble sort, binary search)
public class SortingAlgo {
private int[] arrayVals = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
// print an array
private void printArray() {
System.out.println("---printing arrays");
for (int i = 0; i < arrayVals.length; i++) {
System.out.println(String.format("---value in array at index %d is %d", i, arrayVals[i]));
}
}
// swapping
private void swap(int index1, int index2) {
int temp = arrayVals[index1];
arrayVals[index1] = arrayVals[index2];
arrayVals[index2] = temp;
}
// 1. bubble sort asc algo
private void doABubbleSortASC() {
System.out.println("---doing a bubble sort ASC");
for (int i = arrayVals.length - 1; i >= 1; i--) {
for (int j = 0; j < i; j++) {
if (arrayVals[j] > arrayVals[j + 1]) {
swap(j, j + 1);
System.out.println("---now array is :: " + Arrays.toString(arrayVals));
}
}
}
}
// 2. do a binary search algo - this works well for sorted array(without duplicates)
private void doBinarySearch(int value) {
System.out.println("---doing a binary search :: of " + value);
int lowIndex = 0;
int highIndex = arrayVals.length - 1;
int middleIndex = 0;
while (lowIndex <= highIndex) {
middleIndex = (lowIndex + highIndex) / 2;
if (arrayVals[middleIndex] < value) {
lowIndex = middleIndex + 1;
} else if (arrayVals[middleIndex] > value) {
highIndex = middleIndex - 1;
} else {
System.out.println("---we found the value in Index :: " + middleIndex);
System.out.println("---and the value is :: " + arrayVals[middleIndex]);
break;
}
}
if (lowIndex > highIndex) {
System.out.println("---Item not found, sorry!");
}
}
// main function
public static void main(String[] args) {
SortingAlgo sortingAlgo = new SortingAlgo();
sortingAlgo.printArray();
sortingAlgo.doABubbleSortASC();
sortingAlgo.printArray();
sortingAlgo.doBinarySearch(17);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment