Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

DS-Algos

Created By : Faiq Ahmad


Linear Search Algorithm:-
1. Take the Key from the user and Search the element.
2. If the element is the first element break the Loop.
3. Else Search the element in the entire list one by one.
4. The element would either be at the end of the List or not in the list.
5. The Best Case will be if User searches for the 1st element in the list
at that time it’s complexity will be O(1).
6. In case of worst case the number of elements will be equal to the
number the comparisons so it’s complexity will be O(n).
7. In Average Case We Find the Mean So n(n+1)/2 x 1/n (n and n
cancels). So the Complexity will be O(n).
8. It’s an Space Efficient Algo it’s Space Complexity is O(1).

Binary Search Algorithm:-


1. Find the Mid in the List by Adding the First and Last Index in the
List and dividing by 2.
2. If (A[Mid] == item) return the Mid.
3. Else if the Key is greater than A[Mid] then First = Mid+1.
4. Else Last = Mid – 1.
5. The Best Case Complexity will be O(1).
6. The Worse Case Complexity will O(log n) because if n = 8 then
n/2 = 4 which is 2^2 and n/4 = 2 which 2^1 and we are getting
the equation as n/2^D = 1 So After Simplification we will get
D = log(n).
7. The Worse Case will be O(logn) after Simplifying n/2^D-1.
Sorting Algos:-
Bubble Sort:
1. Find the Size of the Array.
2. Compare the Adjacent Elements by Skipping the last in every
Pass from the Second One.
3. If the Elements are not in Order Swap them.
//Best Case.

Passes Comparisons Swaps


P1 n-1 0
P2 n-2 0
P3 n-3 0
. . .
. . .
Pn-1 1 0
n(n+1)/2 0

= n^2 + n/2
So drop the least Significant and Constants we will get O(n^2).
If we Improve this like that Pass in which no Swap is done then
the Complexity will be O(n).

//Worst Case
Passes Comparisons Swaps
P1 n-1 n-1
P2 n-2 n-2
P3 n-3 n-3
. . .
. . .
Pn-1 1 1
n(n+1)/2 n(n+1)/2

= n(n+1)/2 + 3n(n+1)/2
= 4n(n+1)/2
=4n^2 + 4n /2
So After Dropping the Constants and Least Significant the
Worst Case Complexity will be O(n^2).

The Average Case is also O(n^2).


And it’s Space Efficient So it’s Space Complexity is O(1).

Selection Sort:-
1. Get an Unsorted Array.
2. Set the Min location to 0.
3. Search the Minimum element in the List.
4. Swap with the value at the Location Min.
5. Increment Min to Point to Next Element.
6. Repeat until the List is Sorted.
//Best Case

Passes Comparisons Swaps


P1 n-1 0
P2 n-2 0
P3 n-3 0
. . .
. . .
Pn-1 1 0
n(n+1)/2 0

So its Best Case will be O(n^2).

//Worst Case

Passes Comparisons Swaps


P1 n-1 1
P2 n-2 1
P3 n-3 1
. . .
. . .
Pn-1 1 1
n(n+1)/2 n-1

Again it’s Worst Time Complexity will be O(n^2).

It’s Average Time Complexity is also O(n^2).

It’s an In Memory Algorithm So Space Complexity is O(1).


Insertion Sort : -

1. If it’s the first Element it’s Already Sorted.


2. Pick the Next Element.
3. Compare with all the elements in the Sorted Sub-List.
4. Shift all the elements in the sorted sub-list that is greater
than the value to be sorted.
5. Insert the value.
6. Repeat until the Array is Sorted.

//Best Case

Passes Comparisons Shifts


P1 1 0
P2 2 0
P3 3 0
. . .
. . .
Pn-1 n-1 0
n-1 0

So its Best Complexity is O(n).

//Worst Case

Passes Comparisons Shifts


P1 1 1
P2 2 2
P3 3 3
. . .
. . .
Pn-1 n-1 n-1
n(n+1)/2 n(n+1)/2

So it’s Worst Case Complexity will be O(n^2).

Its Average Case Complexity will be O(n^2).

It’s an In-Memory Algorithm So its Space Complexity will


be O(1).

Recursive Bubble Sort : -


 STEP 1: If the array size is 1, then return.
 STEP 2: Do One Pass of normal Bubble Sort on the given array. This
will fix the last element of the current subarray.
 STEP 3: Use Recursion for all elements except the last of the
current subarray.

public void RecursiveBubble(int A[], int n){

//Base Condition
if(n == 1){
return;
}

for(int i = 0; i < n-1; i++){


if(A[i] > A[i+1]){
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
RecursiveBubble(A,n-1);

Best Case = O(n)


Worst Case = O(n^2)
Average Case = O(n^2)
Space Complexity = O(n)
.

Cocktail Sort:-

 1. Compare each pair of adjacent elements from the beginning of


an array and, if they are in reversed order, swap them.
 2. If no swap made, then stop: we are done (optimization).
 3. Remove the current last element from the possible comparison
(optimization).

 1.bis. Compare each pair of adjacent elements from the end of an
array and, if they are in reversed order, swap them.
 2.bis. If no swap made, then stop: we are done (optimization).
 3.bis. Remove the current first element from the possible
comparison (optimization).
public void CocktailSort(int A[]){

boolean Swapped = true;


int Start = 0;
int end = A.length;

while(Swapped == true){

Swapped = false;

for(int i = Start; i < end-1; i++){


if(A[i] > A[i+1]){
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
Swapped = true;
}
}
end = end - 1;

for(int i = end-1; i >= Start; i--){


if(A[i] > A[i+1]){
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
Start = Start + 1;
}

Best Case = O(n)


Worst Case = O(n^2)
Average Case = O(n^2)

Auxillary = O(1)

Gnome Sort:-

1. If the flower pot just before and after him are in correct order, then he
moves one step forward.
2. If it is not in correct order, he swaps the pots and moves back one step.
3. At the starting when there is no pot before him, he steps forward and
on reaching the end of the pot line, the list is sorted.

public void GnomeSort(int A[]){

int n = A.length;

int index = 0;

while(index < n){


if(index == 0){
index++;
}
if(A[index] >= A[index - 1]){

index++;

}
else{
int temp = A[index];
A[index] = A[index-1];
A[index - 1] = temp;
index--;
}

Best Case = O(n)


Worst Case = O(n^2)
Average Case = O(n^2)

Space = O(1)

Shell Sort :-

Step 1 − Initialize the value of h


Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted
int n = array.length;
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j
-= interval) {
array[j] = array[j - interval];
}
array[j] = temp;

//Best Case = O(nlogn)


//Worst Case = O(n^2)
//Average Case = O(nlogn)
}
}

Comb Sort:-

1. Create and initialise variables gap and swapped and constant


SHRINK_FACTOR
a) gap = size of the array
b) swapped = false
c) SHRINK_FACTOR = 1.3
2. Set swapped = false
3. Set gap = gap/SHRINK_FACTOR
4. Iterate over the array from i = 0 to i < n - gap:
if array[i] > array[i + gap]
a) swap the elements array[i] and array[i + gap]
b) set swapped = true
5. Repeat steps 2-4 while gap != 1 and swapped = true

int getNextGap(int gap)


{
// Shrink gap by Shrink factor
gap = (gap * 10) / 13;
if (gap < 1)
return 1;
return gap;
}

// Function to sort arr[] using Comb Sort


void Combosort(int arr[])
{
int n = arr.length;

// initialize gap
int gap = n;

// Initialize swapped as true to make sure that


// loop runs
boolean swapped = true;

// Keep running while gap is more than 1 and last


// iteration caused a swap
while (gap != 1 || swapped == true) {
// Find next gap
gap = getNextGap(gap);

// Initialize swapped as false so that we can


// check if swap happened or not
swapped = false;

// Compare all elements with current gap


for (int i = 0; i < n - gap; i++) {
if (arr[i] > arr[i + gap]) {
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i + gap];
arr[i + gap] = temp;

// Set swapped
swapped = true;
}
}
}
}

public void GnomeSort(int A[]){

int n = A.length;

int index = 0;

while(index < n){


if(index == 0){
index++;
}

if(A[index] >= A[index - 1]){

index++;

}
else{
int temp = A[index];
A[index] = A[index-1];
A[index - 1] = temp;
index--;
}

public void ShellSort(int array[]){

int n = array.length;
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j
-= interval) {
array[j] = array[j - interval];
}
array[j] = temp;

//Best Case = O(nlogn)


//Worst Case = O(n^2)
//Average Case = O(nlogn)
}
}

Heap Sort :-

 Step 1 - Construct a Binary Tree with given list of Elements.


 Step 2 - Transform the Binary Tree into Min Heap.
 Step 3 - Delete the root element from Min Heap
using Heapify method.
 Step 4 - Put the deleted element into the Sorted list.
 Step 5 - Repeat the same until Min Heap becomes empty.
 Step 6 - Display the sorted list

public class HeapSort


{
public void sort(int arr[])
{
int n = arr.length;

// Build heap (rearrange array)


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

// call max heapify on the reduced heap


heapify(arr, i, 0);
}
}

// To heapify a subtree rooted with node i which is


// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far


if (r < n && arr[r] > arr[largest])
largest = r;

// If largest is not root


if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;

// Recursively heapify the affected sub-tree


heapify(arr, n, largest);
}
}

Best Case = nlogn


Worst Case = nlogn
Average Case = nlogn

Space = O(1)

Bucket Sort:-

1. Set up an array of initially empty "buckets".


2. Scatter: Go over the original array, putting each object in its
bucket.
3. Sort each non-empty bucket.
4. Gather: Visit the buckets in order and put all elements back into
the original array.

import java.util.ArrayList;
import java.util.Collections;

public class BucketSort {


public void bucketSort(float[] arr, int n) {
if (n <= 0)
return;
@SuppressWarnings("unchecked")
ArrayList<Float>[] bucket = new ArrayList[n];

// Create empty buckets


for (int i = 0; i < n; i++)
bucket[i] = new ArrayList<Float>();

// Add elements into the buckets


for (int i = 0; i < n; i++) {
int bucketIndex = (int) arr[i] * n;
bucket[bucketIndex].add(arr[i]);
}

// Sort the elements of each bucket


for (int i = 0; i < n; i++) {
Collections.sort((bucket[i]));
}

// Get the sorted array


int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0, size = bucket[i].size(); j < size; j++) {
arr[index++] = bucket[i].get(j);
}
}
}

Best Case = O(n+k)


Worst Case = O(n^2)
Average Case = O(n)
Cycle Sort : -

1. Create a loop that begins at the beginning of the array and ends
at the second to last item in the array
2. Save the value of the item at the current index.
In our example, we named our value item .
3. Make a copy of the current index.
In our example, we named our index copy currentIndexCopy .
4. Create an additional loop that begins at one
index after the currentIndex and ends at the last item in the
array. Inside of this loop, compare item to the value of the item at
the index of the loop we’re currently in. If the value at the index of
the child loop is less than item , increment the currentIndexCopy .
5. Once the loop from step 4 is completed, check to see if
the currentIndexCopy has changed. If it has not changed, take a
step forward in the loop.
6. If the value at currentIndexCopy is the same as item ,
increment currentIndexCopy . This will skip all duplicate values.
7. Save the item at the currentIndexCopy (we called our temp ),
place item into the index of currentIndexCopy , and update the
value of item to temp .
8. Create an additional loop that runs
until currentIndex and currentIndexCopy are the same.
9. Inside the loop, save currentIndex to currentIndexCopy .
10. Repeat steps 4, 6 and 7.
public static void cycleSort(int arr[], int n)
{
// count number of memory writes
int writes = 0;

// traverse array elements and put it to on


// the right place
for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) {
// initialize item as starting point
int item = arr[cycle_start];

// Find position where we put the item. We basically


// count all smaller elements on right side of item.
int pos = cycle_start;
for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos++;

// If item is already in correct position


if (pos == cycle_start)
continue;

// ignore all duplicate elements


while (item == arr[pos])
pos += 1;

// put the item to it's right position


if (pos != cycle_start) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}

// Rotate rest of the cycle


while (pos != cycle_start) {
pos = cycle_start;

// Find position where we put the element


for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos += 1;

// ignore all duplicate elements


while (item == arr[pos])
pos += 1;

// put the item to it's right position


if (item != arr[pos]) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
}
}

Best = O(n^2)
Worst = O(n^2)
Average = O(n^2)
Count Sort:-
class CountingSort {
void sort(char arr[])
{
int n = arr.length;

// The output character array that will have sorted arr


char output[] = new char[n];

// Create a count array to store count of inidividul


// characters and initialize count array as 0
int count[] = new int[256];
for (int i = 0; i < 256; ++i)
count[i] = 0;

// store count of each character


for (int i = 0; i < n; ++i)
++count[arr[i]];

// Change count[i] so that count[i] now contains actual


// position of this character in output array
for (int i = 1; i <= 255; ++i)
count[i] += count[i - 1];

// Build the output character array


// To make it stable we are operating in reverse order.
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
// Copy the output array to arr, so that arr now
// contains sorted characters
for (int i = 0; i < n; ++i)
arr[i] = output[i];
}

Best Case = O(n+k)


Worse Case = O(n+k)
Average Case = O(n+k)

Space = O(n+k)

You might also like