1.
Selection Sort
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with
# the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),
2. Merge Sort
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i=j=k=0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
3. Sortare prin insertie
def insertSort(l):
"""
sort the element of the list
l - list of element
return the ordered list (l[0]<l[1]<...)
"""
for i in range(1,len(l)):
ind = i-1
a = l[i]
#insert a in the right position
while ind>=0 and a<l[ind]:
l[ind+1] = l[ind]
ind = ind-1
l[ind+1] = a
4. Sortare prin selectie directa
def directSelectionSort(l):
"""
sort the element of the list
l - list of element
return the ordered list (l[0]<l[1]<...)
"""
for i in range(0,len(l)-1):
#select the smallest element
for j in range(i+1,len(l)):
if l[j]<l[i]:
l[i],l[j] = l[j],l[i]
5. Sortarea bulelor
def bubbleSort(l):
sorted = False
while not sorted:
sorted = True # assume the list is already sorted
for i in range(len(l)-1):
if l[i+1]<l[i]:
l[i], l[i + 1] = l[i + 1], l[i]
sorted = False # the list is not sorted yet
6. Quick Sort
def partition(arr, low, high):
i = (low-1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr, low, high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)