0% found this document useful (0 votes)
32 views5 pages

Sort em Python

This document contains Python code that implements and tests various sorting algorithms (selection sort, bubble sort, merge sort, quicksort) and a binary search function. It defines functions for each algorithm, applies a timing decorator to measure runtime, and calls the main function which sorts sample data using each algorithm and inserts a new item into a sorted list using binary search.

Uploaded by

adrianoucam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views5 pages

Sort em Python

This document contains Python code that implements and tests various sorting algorithms (selection sort, bubble sort, merge sort, quicksort) and a binary search function. It defines functions for each algorithm, applies a timing decorator to measure runtime, and calls the main function which sorts sample data using each algorithm and inserts a new item into a sorted list using binary search.

Uploaded by

adrianoucam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

import cProfile

import time

vetor=[7,5,8,6,1,0,2,4,9,3]
original=[7,5,8,6,1,0,2,4,9,3]

def timing(f):
def wrap(*args, **kwargs):
time1 = time.time()
ret = f(*args, **kwargs)
time2 = time.time()
print('{:s} function took {:.5f} ms'.format(f.__name__, (time2-
time1)*10000.0))

return ret
return wrap

@timing
def sort2(vet):
i=0
j=0
for i in range(len(vet)):
for j in range(len(vet)):
if vet[i]<vet[j]:
t=vet[j]
vet[j]=vet[i]
vet[i]=t
return vet

def merge(arr, l, m, r):


n1 = m - l + 1
n2 = r - m

# create temp arrays


L = [0] * (n1)
R = [0] * (n2)

# Copy data to temp arrays L[] and R[]


for i in range(0, n1):
L[i] = arr[l + i]

for j in range(0, n2):


R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if there


# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted

@timing
def mergeSort(arr, l, r):
if l < r:

# Same as (l+r)//2, but avoids overflow for


# large l and h
m = l+(r-l)//2

# Sort first and second halves


mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
return arr

@timing

def selectionSort(array):
size=len(array)
for ind in range(size):
min_index = ind
for j in range(ind + 1, size):
if array[j] < array[min_index]:
min_index = j
(array[ind], array[min_index]) = (array[min_index], array[ind])
return array

@timing
def quick_sort(lista, inicio, fim):
if inicio > fim:
return
anterior = inicio
posterior = fim
pivo = lista[inicio]

while anterior < posterior:


while anterior < posterior and lista[posterior] > pivo:
posterior = posterior - 1

if anterior < posterior:


lista[anterior] = lista[posterior]
anterior = anterior + 1

while anterior < posterior and lista[anterior] <= pivo:


anterior = anterior + 1

if anterior < posterior:


lista[posterior] = lista[anterior]
posterior = posterior - 1

lista[anterior] = pivo

quick_sort(lista, inicio, anterior - 1)


quick_sort(lista, anterior + 1, fim)
return lista

@timing
def bubbleSort(arr):
n = len(arr)
swapped = False
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if not swapped:
return arr
return arr
@timing
def binarySearch(arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
def insert_item(array,valor):
i = binarySearch(array, 0, len(original)-1, valor)
if i>0:
array.insert(i,valor)
else:
for i in range(len(array),1):
if (array[i-1]<=valor) or (array[i]>=valor):
#array.insert(i,valor)
print(i,'xxx',valor)
break

return array

def main():
global vetor
global original
print ('-------------------------------------------------------------
-----')
print ('original ',original)
print (' ---- ORDENADO selectionsort --------')
print (selectionSort(vetor))
vetor=original
print ('original ',vetor)
print (' ---- ORDENADO bubblesort --------')
print (bubbleSort(vetor))
original=[7,5,8,6,1,0,2,4,9,3]
print ('original ',original)
print (' ---- ORDENADO mergeSort --------')
vetor=original
print (mergeSort(vetor,0,len(vetor)-1))

vetor=[7,5,8,6,1,0,2,4,9,3]
print ('original ',vetor)
print (' ---- ORDENADO QuickSort --------')
print (quick_sort(vetor,0,len(vetor)-1))
print (' ---- Procurando um elemento vetor fora de ordem --------')
x=5
original=[7,5,8,6,1,0,2,4,9,3]
print ('original ',original)
result = binarySearch(original, 0, len(original)-1, x)
print (' ---- um elemento na posicao vetor ordenado --------
',result)
result = binarySearch(vetor, 0, len(original)-1, x)
print (' ---- um elemento na posicao --------',result)
vetor=insert_item(vetor,55)
print (vetor)

if __name__ == '__main__':
main()

You might also like