.

Showing posts with label algorithms. Show all posts
Showing posts with label algorithms. Show all posts

Wednesday, August 3, 2016

BinaryGap Algo and implementation in Python

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Implementation 1:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def solution(N):
    bin_list = []
    bin_gap = 0
    pre_gap = 0
    flag = False
    while(N > 0):
        if N % 2 == 0:
            bin_list.append(0)
        else:
            bin_list.append(1)
        N = N // 2
    for i in bin_list:
        if i == 1:
            flag = True
            if (bin_gap > pre_gap):
                pre_gap = bin_gap
            bin_gap = 0
        elif (i == 0 and flag is True):
            bin_gap += 1
        else:
            continue
    return pre_gap


Implementation 2:
 
1
2
def solution(N):
    return len(max((bin(N)[2:]).split('1' - 1), key=len))



Wednesday, July 22, 2015

Selection Sort - using Python

Selection sort is also one of the basic sort algorithms and run in quadratic time O(n^2) same as Insertion sort.  The Selection sort is better than Insertion sort in terms of space complexity but has slower  than insertion sort in terms of time complexity.

Here we do not swap numbers after every comparison; rather we find the smallerst/largest numbers, save it in a temporary variable and replace it with the leftmost element in right array. In result we get sorted array on left hand side.

Explanation

Given an unsorted list the algorithm finds the smallest element and swap it with first element. Then it searches for smallest element in list excluding the 1st element  and so on till the list got sorted finally.



Below are the differences between Selection sort and Insertion sort 








Implementation




__author__ = 'Dharmjit'
def selection_sort(list):
    for index in range(0, len(list)):
        iSmall = index
        for i in range(index,len(list)):
            if list[iSmall] > list[i]:
                iSmall = i
        list[index], list[iSmall] = list[iSmall], list[index]
    return list

if __name__ == '__main__':
    print(selection_sort([5,2,4,6,1,3,]))

Wednesday, July 8, 2015

Insertion Sort - using Python

Talk about Algorithms and sorting comes to mind at first as it is the king of algorithms. Not only because there are many sorting algorithms but sorting is the fundamental operation in computing. Sorting means arranging items in some specific order and we see these all the times when working on our files or folder and working in database when we need records in some certain fashion. Sorting also find its use in searching and other algorithms.

There are many sorting algorithms and we will describe each algorithm and its implementation one post at a time.


Insertion sort

Insertion Sort is one of the simplest sorting algorithm. It is same as we sort  cards in our hand. We look at cards from left to right pick the unsorted card and insert it at correct position.

Explanation


For explaining the insertion sort algorithm we have taken the below unsorted list having 5 elements.

5
1
3
2
4


On first Iteration Second element will be compared with the first element it is smaller than first element they are swapped resulting in below list

1
5
3
2
4

  
On second iteration 3rd element will be checked against 1st and 2nd element and below list is formed.

1
3
5
2
4


And so on till the last element...

1
2
3
5
4

  
Final sorted list

1
2
3
4
5



Implementation


__author__ = 'Dharmjit'
def InsertionSort(list):
    for index in range(1,len(list)):
        curr = list[index]
        position = index

        while position > 0 and list[position-1] > curr:
            list[position] = list[position-1]
            position = position - 1

        list[position] = curr
    return list

l = [2,1,5,3,9,6,7]
print(InsertionSort(l))
[1,2,3,5,6,7,9]
Time complexity

Best Case Scenario:- If the list is already sorted the insertion algorithm runs in O(n) time which is linear

Worst Case Scenario:- When the List is sorted in reverse order, it will take o(n^2) time which is quadratic.