0% found this document useful (0 votes)
20 views

Tugas-02 (Analisis Algoritma)

The document discusses 10 different sorting algorithms: bubble sort, selection sort, insertion sort, merge sort, quicksort, counting sort, radix sort, bucket sort, heap sort, and shell sort. For each algorithm, Python code examples are provided to demonstrate how to implement the algorithm.

Uploaded by

Rafi
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)
20 views

Tugas-02 (Analisis Algoritma)

The document discusses 10 different sorting algorithms: bubble sort, selection sort, insertion sort, merge sort, quicksort, counting sort, radix sort, bucket sort, heap sort, and shell sort. For each algorithm, Python code examples are provided to demonstrate how to implement the algorithm.

Uploaded by

Rafi
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/ 12

TUGAS-02 (UTS)

Pengurutan (sorting) adalah yang sangat penting saat memanipulasi


data. Ketika kita mengurutkan data, data akan terlihat rapi dan mudah
dibaca. Sehingga memudahkan juga dalam menganalisa.

Kenapa kita perlu algoritma untuk mengurutkan sesuatu? Saat


pengurutan data dilakukan, program akan mengkalkulasi dan
membandingkan setiap data agar dapat menemukan mana yang
terbesar dan terkecil.

Diketahui beberapa Teknik Pengurutan Dalam Script Phyton

1. Bubble Sort Algorithm


def bubble_sort(array):
n = len(array) # jumlah list
# perulangan pertama
for i in range(n):
# perulangan kedua
for j in range(n - i - 1):
# bandingkan masing" elemen
if array[j] > array[j + 1]:
# jika lebih besar, tukar.
array[j], array[j + 1] = array[j + 1], array[j]
return array
unordered = [5, 3, 4, 8, 1, 2, 9, 6]
print(bubble_sort(unordered))

2. Selection Sort Algorithm


def selection_sort(arr):
n = len(arr)
# perulangan list elemen
for i in range(n):
# cari nilai elemen terendah
# yang masih tersedia
min_idx = i
for j in range(i+1, n):
if arr[min_idx] > arr[j]:
min_idx = j

# tukar dengan nilai elemen ke-i


arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
listku = [64, 25, 12, 22, 11]
print(selection_sort(listku))

3. Insertion Sort Algorithm


def insertion_sort(array):
# perulangan pertama
for i in range(1, len(array)):
# ini elemen yang akan kita posisikan
key_item = array[i]
# kunci index posisi
j = i - 1
# lakukan perulangan kedua
while j >= 0 and array[j] > key_item:
# menggeser elemen yang lain
array[j + 1] = array[j]
j -= 1
# memposisikan elemen
array[j + 1] = key_item

return array
unordered = [91, 21, 37, 77, 82]
print(insertion_sort(unordered))

4. Merger Sort Algorithm


5. # MergeSort in Python
6.
7.
8. def mergeSort(array):
9. if len(array) > 1:
10.
11. # r is the point where the array is divided into two subarrays
12. r = len(array)//2
13. L = array[:r]
14. M = array[r:]
15.
16. # Sort the two halves
17. mergeSort(L)
18. mergeSort(M)
19.
20. i = j = k = 0
21.
22. # Until we reach either end of either L or M, pick larger among
23. # elements L and M and place them in the correct position at
A[p..r]
24. while i < len(L) and j < len(M):
25. if L[i] < M[j]:
26. array[k] = L[i]
27. i += 1
28. else:
29. array[k] = M[j]
30. j += 1
31. k += 1
32.
33. # When we run out of elements in either L or M,
34. # pick up the remaining elements and put in A[p..r]
35. while i < len(L):
36. array[k] = L[i]
37. i += 1
38. k += 1
39.
40. while j < len(M):
41. array[k] = M[j]
42. j += 1
43. k += 1
44.
45.
46.# Print the array
47.def printList(array):
48. for i in range(len(array)):
49. print(array[i], end=" ")
50. print()
51.
52.
53.# Driver program
54.if __name__ == '__main__':
55. array = [6, 5, 12, 10, 9, 1]
56.
57. mergeSort(array)
58.
59. print("Sorted array is: ")
60. printList(array)
5. Quicksort Algorithm
# Quick sort in Python

# function to find the partition position


def partition(array, low, high):

# choose the rightmost element as pivot


pivot = array[high]

# pointer for greater element


i = low - 1

# traverse through all elements


# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1

# swapping element at i with element at j


(array[i], array[j]) = (array[j], array[i])

# swap the pivot element with the greater element specified by i


(array[i + 1], array[high]) = (array[high], array[i + 1])

# return the position from where partition is done


return i + 1

# function to perform quicksort


def quickSort(array, low, high):
if low < high:

# find pivot element such that


# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)

# recursive call on the left of pivot


quickSort(array, low, pi - 1)
# recursive call on the right of pivot
quickSort(array, pi + 1, high)

data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)

6. Counting Sort Algorithm


# Quick sort in Python

# function to find the partition position


def partition(array, low, high):

# choose the rightmost element as pivot


pivot = array[high]

# pointer for greater element


i = low - 1

# traverse through all elements


# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1

# swapping element at i with element at j


(array[i], array[j]) = (array[j], array[i])

# swap the pivot element with the greater element specified by i


(array[i + 1], array[high]) = (array[high], array[i + 1])
# return the position from where partition is done
return i + 1

# function to perform quicksort


def quickSort(array, low, high):
if low < high:

# find pivot element such that


# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)

# recursive call on the left of pivot


quickSort(array, low, pi - 1)

# recursive call on the right of pivot


quickSort(array, pi + 1, high)

data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)

7. Radix Sort Algorithm


1. # Radix sort in Python
2.
3.
4. # Using counting sort to sort the elements in the basis of significant
places
5. def countingSort(array, place):
6. size = len(array)
7. output = [0] * size
8. count = [0] * 10
9.
10. # Calculate count of elements
11. for i in range(0, size):
12. index = array[i] // place
13. count[index % 10] += 1
14.
15. # Calculate cumulative count
16. for i in range(1, 10):
17. count[i] += count[i - 1]
18.
19. # Place the elements in sorted order
20. i = size - 1
21. while i >= 0:
22. index = array[i] // place
23. output[count[index % 10] - 1] = array[i]
24. count[index % 10] -= 1
25. i -= 1
26.
27. for i in range(0, size):
28. array[i] = output[i]
29.
30.
31.# Main function to implement radix sort
32.def radixSort(array):
33. # Get maximum element
34. max_element = max(array)
35.
36. # Apply counting sort to sort elements based on place value.
37. place = 1
38. while max_element // place > 0:
39. countingSort(array, place)
40. place *= 10
41.
42.
43.data = [121, 432, 564, 23, 1, 45, 788]
44.radixSort(data)
45.print(data)
8. Bucket Sort Algorithm
1. # Bucket Sort in Python
2.
3.
4. def bucketSort(array):
5. bucket = []
6.
7. # Create empty buckets
8. for i in range(len(array)):
9. bucket.append([])
10.
11. # Insert elements into their respective buckets
12. for j in array:
13. index_b = int(10 * j)
14. bucket[index_b].append(j)
15.
16. # Sort the elements of each bucket
17. for i in range(len(array)):
18. bucket[i] = sorted(bucket[i])
19.
20. # Get the sorted elements
21. k = 0
22. for i in range(len(array)):
23. for j in range(len(bucket[i])):
24. array[k] = bucket[i][j]
25. k += 1
26. return array
27.
28.
29.array = [.42, .32, .33, .52, .37, .47, .51]
30.print("Sorted Array in descending order is")
31.print(bucketSort(array))

9. Heap Sort Algorithm


# Heap Sort in python
def heapify(arr, n, i):
# Find largest among root and children
largest = i
l = 2 * i + 1
r = 2 * i + 2

if l < n and arr[i] < arr[l]:


largest = l

if r < n and arr[largest] < arr[r]:


largest = r

# If root is not largest, swap with largest and continue heapifying


if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)

def heapSort(arr):
n = len(arr)

# Build max heap


for i in range(n//2, -1, -1):
heapify(arr, n, i)

for i in range(n-1, 0, -1):


# Swap
arr[i], arr[0] = arr[0], arr[i]

# Heapify root element


heapify(arr, i, 0)

arr = [1, 12, 9, 5, 6, 10]


heapSort(arr)
n = len(arr)
print("Sorted array is")
for i in range(n):
print("%d " % arr[i], end='')

10. Shell Sort Algorithm


32.# Shell sort in python
33.
34.
35.def shellSort(array, n):
36.
37. # Rearrange elements at each n/2, n/4, n/8, ... intervals
38. interval = n // 2
39. while interval > 0:
40. for i in range(interval, n):
41. temp = array[i]
42. j = i
43. while j >= interval and array[j - interval] > temp:
44. array[j] = array[j - interval]
45. j -= interval
46.
47. array[j] = temp
48. interval //= 2
49.
50.
51.data = [9, 8, 3, 7, 5, 6, 4, 1]
52.size = len(data)
53.shellSort(data, size)
54.print('Sorted Array in Ascending Order:')
55.print(data)

11. Linear Search Algorithm


# Linear Search in Python
def linearSearch(array, n, x):
# Going through array sequencially
for i in range(0, n):
if (array[i] == x):
return i
return -1
array = [2, 4, 0, 1, 9]
x = 1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)
12. Binary Search
# Binary Search in python
def binarySearch(array, x, low, high):
if high >= low:
mid = low + (high - low)//2
# If found at mid, then return it
if array[mid] == x:
return mid
# Search the left half
elif array[mid] > x:
return binarySearch(array, x, low, mid-1)
# Search the right half
else:
return binarySearch(array, x, mid + 1, high)
else:
return -1

array = [3, 4, 5, 6, 7, 8, 9]
x = 4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

Ditanyakan: Dari 12 sorting lakukan perhitungan tingkat


kecepatannya dan dan analisa kenapa cepat dan kurang cepat
menurut Anda masing-masing isi tabel 1 sebagai berikut.

Tabel 1.
Perbandingan Teknik Sortir
Data Input (Min.
No. Teknik Sortir Kecepatan (ms) Analisa Hasil
100 Dataset)
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Merge Sort
5. Quick Sort
6. Counting Sort
7. Radix Sort
8. Bucket Sort
9. Heap Sort
10. Shell Sort
11. Linier Sort
12. Binary Sort

You might also like