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

SkipList.py: Added SkipList Data Structure Implementation #236

Closed
wants to merge 14 commits into from
Closed
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
11 changes: 11 additions & 0 deletions bubble_sort/Python/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
24 changes: 24 additions & 0 deletions linear_search/C/linear search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <stdio.h>
void main()
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{ should almost always be at the end of the previous line [whitespace/braces] [4]

Origin: CPPLintBear, Section: all.cpplint.

int a[10], i, item,n,flag=0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing spaces around = [whitespace/operators] [4]

Origin: CPPLintBear, Section: all.cpplint.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing space after , [whitespace/comma] [3]

Origin: CPPLintBear, Section: all.cpplint.

printf("Enter number of elements : ");
scanf("%d",&n);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing space after , [whitespace/comma] [3]

Origin: CPPLintBear, Section: all.cpplint.

printf("\nEnter elements of an array:\n");
for (i=0; i<n; i++)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing spaces around < [whitespace/operators] [3]

Origin: CPPLintBear, Section: all.cpplint.

{printf("Element : ");
scanf("%d", &a[i]);}
printf("\nEnter item to search: ");
scanf("%d", &item);
for (i=0; i<n; i++)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing spaces around < [whitespace/operators] [3]

Origin: CPPLintBear, Section: all.cpplint.

{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{ should almost always be at the end of the previous line [whitespace/braces] [4]

Origin: CPPLintBear, Section: all.cpplint.

if (item == a[i])
{ flag=1;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing spaces around = [whitespace/operators] [4]

Origin: CPPLintBear, Section: all.cpplint.

printf("\nItem found at location %d", i+1);
break;
}
}
if (flag==0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing spaces around == [whitespace/operators] [3]

Origin: CPPLintBear, Section: all.cpplint.

printf("\nItem does not exist.");
getch();
}
16 changes: 16 additions & 0 deletions linear_search/Python/linearsearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
print("************************Linear search*****************************")
arr=list()
n=input("Enter the number of elements : ")
for i in range(int(n)):
ele=int(input("Element : "))
arr.append(int(ele))
key=int(input("Enter the key(elemt to be searched): "))
flag=0
for i in range(int(n)):
if(arr[i]==key):
print("Element Found at ", i+1)
flag=1
if flag==0:
print("Element not found ")
k=input("************************* Press Enter to Exit****************")

75 changes: 75 additions & 0 deletions merge_sort/Python/merge_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include<stdio.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;

mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");
printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
47 changes: 47 additions & 0 deletions queue/Python/queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Queue:
def __init__(self, capacity):
self.front = self.size = 0
self.rear = capacity -1
self.Q = [None]*capacity
self.capacity = capacity
def isFull(self):
return self.size == self.capacity
def isEmpty(self):
return self.size == 0
def EnQueue(self, item):
if self.isFull():
print("Full")
return
self.rear = (self.rear + 1) % (self.capacity)
self.Q[self.rear] = item
self.size = self.size + 1
print("%s enqueued to queue" %str(item))

def DeQueue(self):
if self.isEmpty():
print("Empty")
return

print("%s dequeued from queue" %str(self.Q[self.front]))
self.front = (self.front + 1) % (self.capacity)
self.size = self.size -1

def que_front(self):
if self.isEmpty():
print("Queue is empty")

print("Front item is", self.Q[self.front])
def que_rear(self):
if self.isEmpty():
print("Queue is empty")
print("Rear item is", self.Q[self.rear])
if __name__ == '__main__':

queue = Queue(30)
queue.EnQueue(10)
queue.EnQueue(20)
queue.EnQueue(30)
queue.EnQueue(40)
queue.DeQueue()
queue.que_front()
queue.que_rear()
53 changes: 53 additions & 0 deletions quicksort/Python/quick_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include<stdio.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high- 1; j++)
{

if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
}

int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

109 changes: 109 additions & 0 deletions skip_list/Python/SkipList.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
'''
Skip list is a probabilistic data structure that allows efficient search,
insertion and removal operations.
It allows fast search within an ordered sequence of elements,
O(log(n)) complexity.

Wikipedia Page: https://en.wikipedia.org/wiki/Skip_list
'''
from random import randint, seed
import time
class SkipNode:
'''
A single node in a SkipList data structure,
which is similar to a normal linked list node.
'''
def __init__(self,height=0,elem=None):
self.elem=elem
self.next=[None]*height

class SkipList:
def __init__(self):
# This will set the head node of the list.
self.head=SkipNode()
self.len=0
self.maxHeight=0
def __len__(self):
return self.len
'''
The Search operation takes O(log(n)) time complexity
as compared to O(n) in classical linked list.
'''
def find(self,elem,update=None):
if(update==None):
update = self.updateList(elem)
if(len(update)>0):
candidate = update[0].next[0]
if(candidate!=None and candidate.elem==elem):
return candidate
return None
'''
This function returns a randomized hieght for insertion algorithm.
'''
def randomHeight(self):
height=1
while randint(1,2)!=1:
height+=1
return height
'''
This function returns the skip list that is below the element
which is closest and smaller than the element that is required to find.
'''
def updateList(self,elem):
update=[None]*self.maxHeight
x=self.head
for i in reversed(range(self.maxHeight)):
while x.next[i]!=None and x.next[i].elem<elem:
x=x.next[i]
update[i]=x
return update
'''
This function inserts an element in the correct possition.
The insertion operation takes O(n) time complexity
'''
def insert(self,elem):
node=SkipNode(self.randomHeight(),elem)
self.maxHeight=max(self.maxHeight,len(node.next))
while(len(self.head.next)<len(node.next)):
self.head.next.append(None)
update=self.updateList(elem)
if(self.find(elem, update)==None):
for i in range(len(node.next)):
node.next[i]=update[i].next[i]
update[i].next[i]=node
self.len+=1
'''
This function will remove the specified element from the list.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line contains following spacing inconsistencies:

  • Trailing whitespaces.

Origin: SpaceConsistencyBear, Section: all.pyjava.

The issue can be fixed by applying the following patch:

--- a/tmp/tmpphsfotv0/skip_list/Python/SkipList.py
+++ b/tmp/tmpphsfotv0/skip_list/Python/SkipList.py
@@ -81,7 +81,7 @@
             self.len += 1
 
     '''
-        This function will remove the specified element from the list. 
+        This function will remove the specified element from the list.
         The deletion operation in Skip List takes O(log(n)) time.
     '''
     def remove(self, elem):

The deletion operation in Skip List takes O(log(n)) time.
'''
def remove(self,elem):
update=self.updateList(elem)
x=self.find(elem,update)
if(x!=None):
for i in reversed(range(len(x.next))):
update[i].next[i]=x.next[i]
if(self.head.next[i]==None):
self.maxHeight-=1
self.len-=1
'''
This function will print the entier Data Structure,
level by level (top to bottom)
'''
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line contains following spacing inconsistencies:

  • Trailing whitespaces.

Origin: SpaceConsistencyBear, Section: all.pyjava.

The issue can be fixed by applying the following patch:

--- a/tmp/tmpphsfotv0/skip_list/Python/SkipList.py
+++ b/tmp/tmpphsfotv0/skip_list/Python/SkipList.py
@@ -96,7 +96,7 @@
 
     '''
         This function will print the entier Data Structure, level by level (top to bottom)
-    '''       
+    '''
     def printList(self):
         for i in range(len(self.head.next)-1, -1, -1):
             x = self.head

def printList(self):
for i in range(len(self.head.next)-1, -1, -1):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line contains following spacing inconsistencies:

  • Trailing whitespaces.

Origin: SpaceConsistencyBear, Section: all.pyjava.

The issue can be fixed by applying the following patch:

--- a/tmp/tmphyrtd5og/skip_list/Python/SkipList.py
+++ b/tmp/tmphyrtd5og/skip_list/Python/SkipList.py
@@ -56,7 +56,7 @@
             while x.next[i]!=None and x.next[i].elem<elem:
                 x=x.next[i]
             update[i]=x
-        return update        
+        return update
     '''
         This function inserts an element in the correct possition.
         The insertion operation takes O(n) time complexity

x=self.head
while(x.next[i]!=None):
print(x.next[i].elem,)
x=x.next[i]
print('')
if __name__ == "__main__":
skipList = SkipList()
print("Insertion Started")
t0=time.time()
for i in range(1000000):
skipList.insert(i)
print("Time taken to insert 1M elements: "+str(time.time()-t0)+" s.")
print("Total Size = "+str(len(skipList)))
t0 = time.time()
print(skipList.find(596536)!=None)
print("Time taken to search in a list of size 1M: "+str(time.time()-t0)+" s.")