algorithm and programming - mybogi.files.wordpress.com · feh1h3 - algoritma dan pemrograman b...
TRANSCRIPT
www.telkomuniversity.ac.id
Data Types
• Integral Types: char, signed char, unsigned char short, signed sort, unsigned short int, signed int, unsigned int long, signed long, unsigned long
• Floating Types: float, double, long double
• Enumerated Types: array
• User-defined Types
• Memory Types: pointer, string
www.telkomuniversity.ac.id
Data Types: Enumerated: [Array]
• Array = matrix or group of (similar) data types example: int grade0, grade1, grade2; /* is equal with */
int grade[3]; /* is 1-dimensional array, while */
int grade[2][3]; /* is a 2-dimensional array */
www.telkomuniversity.ac.id
Array
• Array is a group of variables with the same data type. Just like matrix, it needs index(es) to find a specific value stored inside the array
• Example: 1-dimensional array of integer array[0] = 23
• Example: 2-dimensional array of char array[1][2] = ‘L’
index 0 1 2 3
value 23 -10 19 -73
index 0 1 2 3
0 B o G i
1 u G L y
www.telkomuniversity.ac.id
Using Array in C: Data Declaration
#include <stdio.h>
int main(void){
int i, j;
int array_of_int[4]={23,-10,19,-73};
int array_of_char[2][4]={{'B','o','G','i'},{'u','G','L','y'}};
for (i=0; i<4; i++){printf("%d ", array_of_int[i]);}
for (i=0; i<2; i++){
for (j=0; j<4; j++){
printf("%c ", array_of_char[i][j]);}
printf("\n");}
return 0;
}
index 0 1 2 3
value 23 -10 19 -73
index 0 1 2 3
0 B o G i
1 u G L y
www.telkomuniversity.ac.id
Using Array in C: Function
#include <stdio.h>
float average(int array_of_int[]){
int i, total=0;
for (i=0; i<4; i++){
total+=array_of_int[i];
}
return total/4;
}
int main(void){
int array_of_int[4]={23,-10,19,-73};
float avg;
avg=average(array_of_int);
printf("Average score is: %.4f", avg);
return 0;
}
index 0 1 2 3
value 23 -10 19 -73
www.telkomuniversity.ac.id
Searching and Sorting
Course Number : FEH1H3
CLO : 2
Week : 11-13
www.telkomuniversity.ac.id
Searching
Can you find me? 0 0 0 0 0 O 0 0 0
www.telkomuniversity.ac.id
Searching Algorithm
Searching algorithm is defined as information retrieval from a stored data structure or calculated in the search space of a problem domain. Examples of such structures include but are not limited to a linked list, an array data structure, or a search tree. The appropriate search algorithm often depends on the data structure being searched, and may also include prior knowledge about the data. Examples: 1. Linear / Sequential Search 2. Binary Search
www.telkomuniversity.ac.id
Sequential Search
• Searching element_to_find within the data structure by comparing one-by-one in linear / sequence order until the element_to_find is found or end_of_data is reached
• Return either the place where it’s found or any attribute related to the element_to_find
index 0 1 2 3
11001 11002 11003 11004
Dwayne The Rock Johnson
www.telkomuniversity.ac.id
Sequential Search: Example (Animated)
element_to_find = 5
return = place where it’s found
is this 5?
= 5
index 0 1 2 3 4 5 6 7 8 9
value 3 8 1 4 4 5 7 5 2 6
www.telkomuniversity.ac.id
Sequential Search: Algorithm
for (data_index = 0; data_index < data_length; data_index++)
if (data[data_index] == element_to_find) found = data_index
index 0 1 2 3 4 5 6 7 8 9
value 3 8 1 4 4 5 7 5 2 6
data_index element_to_find found
0 5 X
1 5 X
2 5 X
3 5 X
4 5 X
5 5 5
www.telkomuniversity.ac.id
Binary Search
• Only applicable to already sorted data
• Searching element_to_find within the data structure by comparing the middle part of the data until the element_to_find is found
• Return either the place where it’s found or any attribute related to the element_to_find
• Faster than sequential search by ln(N)
www.telkomuniversity.ac.id
Binary Search: Example (Animated)
element_to_find = 5
return = place where it’s found
is this 5? if not, is it less or bigger than 5?
= 2
index 0 1 2 3 4 5 6 7 8 9
value 1 2 5 6 8 9 9 11 14 15
min = mid = max =
0 5 9
0 3 5
0 2 3
www.telkomuniversity.ac.id
Binary Search: Algorithm
min = 0
max = data_length
mid = round((min+max)/2)
do
if (data[mid] == element_to_find) found = mid
else
if (data[mid] > element_to_find
max = mid
mid = round((min+max)/2)
else
min = mid
mid = round((min+max)/2)
while (found == X)
min mid max found
0 5 9 X
index 0 1 2 3 4 5 6 7 8 9
value 1 2 5 6 8 9 9 11 14 15
www.telkomuniversity.ac.id
Example: UAS-SP06
Using binary search, find 42:
data =
[ 2, 3, 9, 17, 18, 24, 36, 39, 42, 54, 60, 65, 79, 82, 94, 108]
What is the value of min, mid, and max on 3rd iteration?
www.telkomuniversity.ac.id
Exercises
www.telkomuniversity.ac.id
Sorting
Biggest to Smallest or Smallest to Biggest?
www.telkomuniversity.ac.id
Sorting Algorithm
Sorting algorithm is defined as an algorithm that puts elements of a list in a certain order (ascending or descending). The most-used orders are numerical order and lexicographical order. Ascending order sorts the data from smallest to biggest. Descending order sorts the data from biggest to smallest. The data is often taken to be in an array, which allows random access, rather than a list, which only allows sequential access. Examples: 1. Bubble Sort 2. Selection Sort 3. Insertion Sort
www.telkomuniversity.ac.id
Bubble Sort
• Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order
• Worst-case performance : O(n2)
• Best-case performance : O(n)
www.telkomuniversity.ac.id
Bubble Sort: Example
www.telkomuniversity.ac.id
Bubble Sort: Example
Ascending (from smallest to the BIGest)
index 0 1 2 3 4 5 6 7 8 9
value 3 8 1 4 4 5 7 5 2 6
is left < right? if not, swap
1 8
www.telkomuniversity.ac.id
Selection Sort
• Selection sort divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted
• The algorithm finds the smallest (or largest) element in the unsorted sublist, swapping it with the leftmost unsorted element
• Worst-case performance : О(n2) comparisons, О(n) swaps
• Best-case performance : О(n2) comparisons, О(n) swaps
www.telkomuniversity.ac.id
Selection Sort: Example 1
www.telkomuniversity.ac.id
Selection Sort: Example 2
www.telkomuniversity.ac.id
Insertion Sort
• Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there
• Worst-case performance : О(n2) comparisons, O(n) swaps
• Best-case performance : O(n) comparisons, O(1) swaps
www.telkomuniversity.ac.id
Insertion Sort: Example
www.telkomuniversity.ac.id
Counting Sort
• counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items.
• Worst-case performance : О(n2) comparisons, O(n) swaps
• Best-case performance : O(n) comparisons, O(1) swaps
www.telkomuniversity.ac.id
See you on next class
www.telkomuniversity.ac.id
Bubble Sort: Example
Sort: ascending
index 0 1 2 3 4 5 6 7 8 9
value 3 8 1 4 4 5 7 5 2 6
is left < right? if no, swap
www.telkomuniversity.ac.id
Bubble Sort: Algorithm
for (data_index = 0; data_index < data_length; data_index++)
if (data[data_index] == element_to_find) found = data_index
index 0 1 2 3 4 5 6 7 8 9
value 3 8 1 4 4 5 7 5 2 6
data_index element_to_find found
0 5 X
1 5 X
2 5 X
3 5 X
4 5 X
5 5 5
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
Proses dilakukan sebanyak (N-1) tahapan (yang dalam sorting disebut sebagai "pass"). Pada setiap Pass, terdapat looping sebanyak (N-pass) dimulai dari N, N-1, N-2, ..., Pass+1. 1. Untuk setiap dua elemen suksesif TabIntK dan TabIntK-1, K [N..2],
TabIntK-1 < TabIntK (ascending) atau TabIntK-1 > TabIntK (descending), dengan demikian TabIntK harus ditukar dengan TabIntK-1 jika sifat di atas tidak dipenuhi. Karena dilakukan secara berurutan, TabInt1 berisi harga terkecil (ascending) atau berisi harga terbesar (descending).
2. Untuk setiap dua elemen suksesif TabIntK dan TabIntK-1, K [N..3], TabIntK-1 < TabIntK (ascending) atau TabIntK-1 > TabIntK (descending), dengan demikian TabIntK harus ditukar dengan TabIntK-1 jika sifat di atas tidak dipenuhi. Karena dilakukan secara berurutan, TabInt[1..2] terurut
Lakukan sampai N-1, K [N,N-1]
Karena dilakukan secara berurutan, TabInt[1..N] sudah terurut : TabInt1 ≤ TabInt2 ≤ TabInt3 ... ≤ TabIntN (ascending) TabInt1 ≥ TabInt2 ≥ TabInt3 ... ≥ TabIntN (descending)
BUBBLE SORT
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
ALGORITMA BUBBLE SORT ASCENDING
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
PROGRAM C BUBBLE SORT ACENDING
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
Algoritma sorting sederhana yang lain adalah Selection Sort. Ide dasarnya adalah melakukan beberapa kali pass untuk melakukan penyeleksian elemen struktur data. Untuk sorting ascending (menaik), elemen yang paling kecil di antara elemen-elemen yang belum urut, disimpan indeksnya,kemudian dilakukan pertukaran nilai elemen dengan indeks yang disimpan tersebut dengan elemen yang paling depan yang belum urut. Sebaliknya, untuk sorting descending (menurun), elemen yang paling besar yang disimpan indeksnya kemudian ditukar.
SELECTION SORT
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
Proses dilakukan sebanyak (N-1) tahapan (yang dalam sorting disebut sebagai "pass"). Pada setiap Pass, terdapat looping sebanyak (N-pass) dimulai dari pass+1, pass+2,..N. 1. Untuk setiap dua elemen suksesif TabIntindeks dan TabIntK, K [2..N],
TabIntindeks < TabIntK (ascending) atau TabIntindeks > TabIntK (descending), dengan demikian nilai indeks selalu di tukar dengan K jika sifat di atas tidak dipenuhi. Karena dilakukan secara berurutan, TabInt1 = TabIntindeks berisi harga terkecil (ascending) atau berisi harga terbesar (descending).
2. Untuk setiap dua elemen suksesif TabIntpass dan TabIntK, K [3..N], TabIntindeks < TabIntK (ascending) atau TabIntindeks > TabIntK (descending), dengan demikian nilai indeks selalu di tukar dengan K jika sifat di atas tidak dipenuhi. Karena dilakukan secara berurutan, TabInt[1..2] terurut
Lakukan sampai N-1, K [N-1,N]
Karena dilakukan secara berurutan, TabInt[1..N] sudah terurut : TabInt1 ≤ TabInt2 ≤ TabInt3 ... ≤ TabIntN (ascending) TabInt1 ≥ TabInt2 ≥ TabInt3 ... ≥ TabIntN (descending)
SELECTION SORT
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
SELECTION SORT
www.telkomuniversity.ac.id
www.telkomuniversity.ac.id
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
ALGORITMA SELECTION SORT DESCENDING
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
Proses dilakukan sebanyak N tahapan: 1. TabInt1 dianggap sudah tepat tempatnya
2. TabInt2 harus dicarikan tempat yang tepat pada TabInt[1..2], yaitu I
Sisipkan TabInt2 pada TabInti. TabInt [1..2] terurut membesar
3. TabInt3 harus dicarikan tempat yang tepat pada TabInt[1..3], yaitu I Sisipkan TabInt3 pada TabInt3. TabInt [1..3] terurut membesar
N-1 .TabIntN-1 harus dicarikan tempat yang tepat pada TabInt[1..N-1], yaitu I Sisipkan TabIntN-1 pada TabIntii..TabInt [1..N-1] terurut membesar
N. TabInt [1..N] sudah terurut : TabInt1 ≤ TabInt2 ≤ TabInt3 ...... ≤ TabIntN
INSERTION SORT
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
Pada setiap Pass, tabel "terdiri dari" dua bagian : yang sudah terurut yaitu [1..Pass – 1] dan sisanya [Pass..Nmax] yang belum terurut.
Ambil elemen TabIntPass, sisipkan ke dalam TabInt[1..Pass-1] dengan tetap menjaga keterurutan.
Untuk menyisipkan TabIntPass ke TabInti, harus terjadi "pergeseran" elemen tabel TabInt [I..Pass].
Pergeseran ini dapat dilakukan sekaligus dengan pencarian I.
Pencarian dapat dihentikan segera dengan memanfaatkan sifat keterurutan TabInt[1..Pass].
Metoda pengurutan ini cukup efisien (≅ N)terutama untuk N yang "kecil".
Terdapat 2 varian : Tanpa Sentinel / Dengan Sentinel
INSERTION SORT
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
ALGORITMA INSERTION SORT ASCENDING
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
ALGORITMA INSERTION SORT WITH SENTINEL ASCENDING
www.telkomuniversity.ac.id FEH1H3 - ALGORITMA DAN PEMROGRAMAN B
PROGRAM C BUBBLE SORT ACENDING