You are on page 1of 13

Sorting

Bubble Sort
Works by swapping adjacent elements if they're not in the desired order

Time Complexity: O(n^2)

Sample Code:
public static void bubbleSort(int[] a) {
boolean sorted = false;
int temp;
while(!sorted) {
sorted = true;
for (int i = 0; i < array.length - 1; i++) {
if (a[i] > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
sorted = false;
}
}
}
}

Insertion Sort
Divides array into sorted and unsorted subarrays and starts working with unsorted parts.
For example, arr = [2 5 8 9 3 1 6]
Here, 2 5 8 9 is the sorted part, this algorithm will start working from 3. It will take 3 and start
sorting until it finds a suitable position.
After first iteration, Arr = [2 3 5 8 9 1 6]

Time Complexity: O(n^2)

Sample Code:
public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int current = a[i];
int j = i - 1;
while(j >= 0 && current < a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = current;
}
}

Selection Sort

35124

15324

12354

12354

12345

12345
Takes the lowest and put it in the starting index and starts searching from (starting
index+1)

Time Complexity: O(n^2)

Sample Code:
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int min = array[i];
int minId = i;
for (int j = i+1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minId = j;
}
}
// swapping
int temp = array[i];
array[i] = min;
array[minId] = temp;
}
}
Merge Sort

7 4 6 1 8 3 9

Divide(Mergesort method) 7 4 6 1 8 3 9

Divide(Mergesort method) 7 4 6 1 8 3 9 9

Divide(Mergesort method) 77 44 66 11 88 33 99

Merge 7 4 6 1 8 3 9 => 47 16 38 9

Merge 47 16 38 9 => 1467 389

Merge 1467 389 => 1346789

Divide the whole array into single char like then sort and at last add them together.
Works in recursion.

Time Complexity: O(nlogn) - Both merge sort and 2 way merge sort,
O(m+n) - for merging, where m and n is the length of two subarrays

Sample Code:
public static void mergeSort(int[] array, int left, int right) {
if (right <= left) return;
int mid = (left+right)/2;
mergeSort(array, left, mid);
mergeSort(array, mid+1, right);
merge(array, left, mid, right);
}

void merge(int[] array, int left, int mid, int right) {


// calculating lengths
int lengthLeft = mid - left + 1;
int lengthRight = right - mid;

// creating temporary subarrays


int leftArray[] = new int [lengthLeft];
int rightArray[] = new int [lengthRight];
// copying our sorted subarrays into temporaries
for (int i = 0; i < lengthLeft; i++)
leftArray[i] = array[left+i];
for (int i = 0; i < lengthRight; i++)
rightArray[i] = array[mid+i+1];

// iterators containing current index of temp subarrays


int leftIndex = 0;
int rightIndex = 0;

// copying from leftArray and rightArray back into array


for (int i = left; i < right + 1; i++) {
// if there are still uncopied elements in R and L, copy minimum of the two
if (leftIndex < lengthLeft && rightIndex < lengthRight) {
if (leftArray[leftIndex] < rightArray[rightIndex]) {
array[i] = leftArray[leftIndex];
leftIndex++;
}
else {
array[i] = rightArray[rightIndex];
rightIndex++;
}
}
// if all the elements have been copied from rightArray, copy the rest of leftArray
else if (leftIndex < lengthLeft) {
array[i] = leftArray[leftIndex];
leftIndex++;
}
// if all the elements have been copied from leftArray, copy the rest of rightArray
else if (rightIndex < lengthRight) {
array[i] = rightArray[rightIndex];
rightIndex++;
}
}
}

Heap Sort
Heap Sort = Insert and create heap + delete the heap element by element.
Divide and Conquer.
Max heap: Root element highest. So deletion will give a descending array. But inserting the
latest deleted element in the last possible index of that same array will eventually give an
ascending array.

Min Heap: Root element lowest. So deletion will give an ascending array.

Heapify: Another way of Heap creation. In heap creation, a new element is added at last and
adjusted towards root(upward). In heapify, this direction is different(downward).

Time Complexity: O(1) to O(logn) -> Heap Insertion


O(logn) to O(nlogn) -> Deletion
O(nlogn) -> Heap Creation
O(n) -> Heapify
O(nlogn) -> Heap Sort

Sample Code:
static void heapify(int[] array, int length, int i) {
int leftChild = 2*i+1;
int rightChild = 2*i+2;
int largest = i;

// if the left child is larger than parent


if (leftChild < length && array[leftChild] > array[largest]) {
largest = leftChild;
}

// if the right child is larger than parent


if (rightChild < length && array[rightChild] > array[largest]) {
largest = rightChild;
}

// if a swap needs to occur


if (largest != i) {
int temp = array[i];
array[i] = array[largest];
array[largest] = temp;
heapify(array, length, largest);
}
}

public static void heapSort(int[] array) {


if (array.length == 0) return;
// Building the heap
int length = array.length;
// we're going from the first non-leaf to the root
for (int i = length / 2-1; i >= 0; i--)
heapify(array, length, i);

for (int i = length-1; i >= 0; i--) {


int temp = array[0];
array[0] = array[i];
array[i] = temp;

heapify(array, i, 0);
}
}

Quick Sort:
Put all the array elements into an array and take 1 length extra than the element number and
put max int(infinity) in that last index. Take the first element as Pivot(it is suggested to take a
middle element as Pivot to avoid the worst case) and start two way searches - one starting
from starting index+1 to onwards(i) and another from last index to backwards(j). If a[i]>a[j] while
(i<j), then swap a[i] with a[j]. If i>j, swap a[j] with pivot.

Divide and Conquer

Time Complexity: O(nlogn) -> Best case, O(n^2) -> Worst Cse

Sample Code:
static int partition(int[] array, int begin, int end) {
int pivot = end;

int counter = begin;


for (int i = begin; i < end; i++) {
if (array[i] < array[pivot]) {
int temp = array[counter];
array[counter] = array[i];
array[i] = temp;
counter++;
}
}
int temp = array[pivot];
array[pivot] = array[counter];
array[counter] = temp;

return counter;
}

public static void quickSort(int[] array, int begin, int end) {


if (end <= begin) return;
int pivot = partition(array, begin, end);
quickSort(array, begin, pivot-1);
quickSort(array, pivot+1, end);
}
Searching

Linear Search
Start from index 0 and traverse one by one to find the element .
Time Complexity: O(n)

Binary Search
Prerequisite is the array have to be sorted
Divide the array into 2 parts
Time Complexity: O(logn), Best case = O(1)

Using Loop:
1. public static void binarySearch(int arr[], int first, int last, int key){
2. int mid = (first + last)/2;
3. while( first <= last ){
4. if ( arr[mid] < key ){
5. first = mid + 1;
6. }else if ( arr[mid] == key ){
7. System.out.println("Element is found at index: " + mid);
8. break;
9. }else{
10. last = mid - 1;
11. }
12. mid = (first + last)/2;
13. }
14. if ( first > last ){
15. System.out.println("Element is not found!");
16. }
17. }

Using Recursion:
1. public static int binarySearch(int arr[], int first, int last, int key){
2. if (last>=first){
3. int mid = first + (last - first)/2;
4. if (arr[mid] == key){
5. return mid;
6. }
7. if (arr[mid] > key){
8. return binarySearch(arr, first, mid-1, key);//search in left subarray
9. }else{
10. return binarySearch(arr, mid+1, last, key);//search in right subarray
11. }
12. }
13. return -1;
14. }

Exponential Search
Prerequisite is a sorted array
Time Complexity: O(1) for best case, O(log2i) for worst case where i is the index number
where the element is.

static int exponentialSearch(int arr[], int n, int x){


// If x is present at first location itself
if (arr[0] == x)
return 0;

// Find range for binary search by


// repeated doubling
int i = 1;
while (i < n && arr[i] <= x)
i = i*2;

// Call binary search for the found range.


return Arrays.binarySearch(arr, i/2, Math.min(i, n-1), x);
}
Fibonacci Search
Prerequisite is sorted array
Time Complexity: O(logn)

public static int fibMonaccianSearch(int arr[], int x,


int n)
{
/* Initialize fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci No.
int fibMMm1 = 1; // (m-1)'th Fibonacci No.
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci

/* fibM is going to store the smallest


Fibonacci Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}

// Marks the eliminated range from front


int offset = -1;

/* while there are elements to be inspected.


Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = min(offset + fibMMm2, n - 1);

/* If x is greater than the value at


index fibMm2, cut the subarray array
from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}

/* If x is less than the value at index


fibMm2, cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}

/* element found. return index */


else
return i;
}

/* comparing the last element with x */


if (fibMMm1 == 1 && arr[n-1] == x)
return n-1;

/*element not found. return -1 */


return -1;
}

A* Search Algorithm:
f(n) = g(n) + h(n), where n is any node, g(n) is the cost to reach the n node, h(n) is the heuristic
value of node n (given).

Dijkstra Algorithm:
For finding the shortest path calculating the weights of the edges by which all nodes are
connected to each other.
Disadvantage: May or may not work for negative edge values
Time Complexity: O(n^2) for worst case

if(d[u]+c[u,v] < d[v])


d[v] = d[u]+c[u,v]

Bellman Ford Algorithm:


Time Complexity: O(n^2) for best case, O(n^3) for worst case.
Functions like the Dijkstra algorithm. Only difference is it performs the similar activities for(n-1)
times, where n is the number of nodes.
Works for negative edges.
Disadvantage: Does not work if there is a circle whose overall weight is negative.

Knapsack Problem:
The key is to find the ratio of profit and weight for each element. Then select elements
according to the descending order (Highest first) of the ratio. Fractions of any element can be
considered to fulfill the total capacity. For example, if there are elements weighed 3 then we can
take 1 or 2 of that element.
M = capacity of output bag
N = number of elements
0/1 Knapsack Problem:
V[i, w] = max{v[i-1, w], v[i-q, w-w[i]]+p[i]}, i = row number, w = column number.
Methods to solve: Tabular or Sets method

Framework - Set of pre-defined functions/classes/objects/Libraries provided by the


system/platform we are working on.

SDK

Software Development Models - Agile Methodology -> Scrum

Flutter lifecycle:
Create state
Init state
Didchange dependency
Build
Dispose - Cleans out the garbage,

How Navigator works

Int[] b = new int[a.length];


for(i = 0; i<a.length: ++i){
Int x = a.length-1;
A[i] = b[x]
--x;
}

You might also like