Skip to content

Instantly share code, notes, and snippets.

@0xInfection
Created March 5, 2020 10:22
Show Gist options
  • Save 0xInfection/2e755b6f752c5281d3b4091c2485d805 to your computer and use it in GitHub Desktop.
Save 0xInfection/2e755b6f752c5281d3b4091c2485d805 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def linSearch(arr, x):
for i in range(0, len(arr)):
if arr[i] == x:
print()
return "Element found!"
def binSearch(arr, x, upper, lower=0):
mid = (upper+lower)/2
if lower > upper:
return "Not found"
if x == arr[mid]:
return "Element found!"
if x > arr[mid]:
return binSearch(arr, x, upper, lower=mid+1)
else:
return binSearch(arr, x, mid-1, lower=lower)
def bubbleSort(arr):
for i in range(0, len(arr)):
for j in range(0, len(arr)):
if arr[i] < arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return arr
def selectSort(arr):
for i in range(0, len(arr)):
mini = i
for j in range(i, len(arr)):
if arr[j] < arr[i]:
mini = j
temp = arr[mini]
arr[mini] = arr[i]
arr[i] = temp
return arr
def insertSort(arr):
for i in range(1, len(arr)):
cp = i
cv = arr[i]
while cp > 0 and arr[cp-1] > cv:
arr[cp] = arr[cp-1]
cp = cp-1
arr[cp] = cv
return arr
if __name__ == "__main__":
s = int(input('[1] Search\n[2] Sort\n\n[-] Your choice: '))
if s == 1:
print("\nYou've selected search.")
f = input("Enter numbers separated by spaces: ")
h = input("Are the numbers sorted? (y/n): ")
arr = [int(i) for i in f.split(' ')]
g = input("Enter search term: ")
if h.lower() == 'y':
print(binSearch(arr, g, upper=len(arr)-1))
else:
print(linSearch(arr, g))
elif s == 2:
print("\nYou've selected sort.")
f = input("Enter numbers separated by spaces: ")
arr = [i for i in f.split(' ')]
d = int(input("[1] Bubble Sort\n[2] Selection Sort\n[3] Insertion Sort\n\n[-] Choice: "))
if d == 1:
print(bubbleSort(arr))
elif d == 2:
print(selectSort(arr))
elif d == 3:
print(insertSort(arr))
else:
print("Invalid choice.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment