0% found this document useful (0 votes)
43 views2 pages

List Manipulation

This document discusses algorithms for manipulating lists: bubble sort, deletion, insertion, selection sort, and binary search. Bubble sort compares adjacent elements and swaps them if out of order. Deletion finds and removes an element from a list. Insertion finds the correct position for a new element and makes space to insert it. Selection sort finds the smallest element and swaps it into the first position, repeating for remaining elements. Binary search uses divide and conquer to efficiently find an element by comparing the search key to the middle element of the list.

Uploaded by

Danish Jamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views2 pages

List Manipulation

This document discusses algorithms for manipulating lists: bubble sort, deletion, insertion, selection sort, and binary search. Bubble sort compares adjacent elements and swaps them if out of order. Deletion finds and removes an element from a list. Insertion finds the correct position for a new element and makes space to insert it. Selection sort finds the smallest element and swaps it into the first position, repeating for remaining elements. Binary search uses divide and conquer to efficiently find an element by comparing the search key to the middle element of the list.

Uploaded by

Danish Jamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

List Manipulation

#Bubble sort

def bsort(l, N):


for i in range(N):
for j in range(N-1):
if l[j] > l[j+1]:
l[j], l[j+1] = l[j+1], l[j]

L = [3, 2, 1]
bsort(L, len(L))
print L

Deletion

def delete(l, n, data):


pos = -1
for j in range(n):
if data == l[j]:
pos = j
break
if pos >= 0:
for i in range(pos, n-1):
l[i] = l[i+1]
return pos

L = [1, 2, 3, 4, 5]
print L
delete(L, len(L), 3)
print L

#Insertion

def insert(l, n, data):


pos = 0
if data <= l[0]:
pos = 0
elif data >= l[n-1]:
pos = n
else:
for i in range(0, n-1):
if l[i] <= data <= l[i+1]:
pos = i+1
break

l.append(0)
for i in range(n, pos, -1):
l[i] = l[i-1]
l[pos] = data

L = [1, 2, 4, 5]
print L
insert(L, len(L), 3)
print L
#Selsort

def SelSort(L, N):


for i in range(N):
sm = L[i]
pos = i
for j in range(i+1, N):
if L[j] < sm:
sm = L[j]
pos = j
L[i], L[pos] = L[pos], L[i]

L = [3, 2, 1]
SelSort(L, len(L))
print L

#Binary search

def BSearch(List, N, Data):


pos = -1
LB = 0
UB = N-1
while LB <= UB:
Mid = (LB+UB)/2
if List[Mid] == Data:
pos = Mid
break
elif Data < List[Mid]:
LB += 1
elif Data > List[Mid]:
UB -= 1
else:
pass
return pos

L = [10,9,8,7,6,5,4,3,2,1]

print BSearch(L, len(L), 4)

You might also like