## Blog Pages

Showing posts with label sort. Show all posts
Showing posts with label sort. Show all posts

### Heap Sort in Python

from heapq import heappop, heappush

def heapsort(list1):

heap = []

for ele in list1:

heappush(heap, ele)

sort = []

while heap:

sort.append(heappop(heap))

return sort

list1 = [27, 21, 55, 15, 60, 4, 11, 17, 2, 87]

print(heapsort(list1))

### Bubble Sort in Python

def bubble_sort(list1):

for i in range(0,len(list1)-1):

for j in range(len(list1)-1):

if(list1[j]>list1[j+1]):

temp = list1[j]

list1[j] = list1[j+1]

list1[j+1] = temp

return list1

list1 = [5, 3, 8, 6, 7, 2]

print("The unsorted list is: ", list1)

print("The sorted list is: ", bubble_sort(list1))

### Program for Cocktail Sort

def cocktailSort(a):

n = len(a)

swapped = True

start = 0

end = n-1

while (swapped==True):

swapped = False

for i in range (start, end):

if (a[i] > a[i+1]) :

a[i], a[i+1]= a[i+1], a[i]

swapped=True

if (swapped==False):

break

swapped = False

end = end-1

for i in range(end-1, start-1,-1):

if (a[i] > a[i+1]):

a[i], a[i+1] = a[i+1], a[i]

swapped = True

start = start+1

a = [5, 1, 4, 2, 8, 0, 2 ,6,7]

cocktailSort(a)

print("Sorted array is:")

for i in range(len(a)):

print ("%d" %a[i]),

### Program for Gnome Sort

def gnomeSort( arr, n):

index = 0

while index < n:

if index == 0:

index = index + 1

if arr[index] >= arr[index - 1]:

index = index + 1

else:

arr[index], arr[index-1] = arr[index-1], arr[index]

index = index - 1

return arr

arr = [ 34, 2, 10, -9]

n = len(arr)

arr = gnomeSort(arr, n)

print ("Sorted seqquence after applying Gnome Sort :")

for i in arr:

print (i)