Desain dan Analisis Algoritma
Pertemuan 6
Brute Force
Salah satu teknik desain algoritma
Brute Force
A straightforward approach to solving problems, usually directly based on the problem statement and definitions of the concepts involved
Examples:
1.Computing a
n(a > 0, n a nonnegative integer) 2.Computing n!
3.Searching for a key of a given value in a list
Apa sorting itu?
A
0≤ A
1≤ A
2≤ … A
n-1≤ A
nBrute Force Sorting
Perhatikan bahwa setelah sorting :
A0 merupaka elemen dengan nilai terkecil
A1 merupaka elemen dengan nilai terkecil setelah A0
…
A merupaka elemen dengan nilai terbesar
Dengan definisi di atas, susunlah algoritma brute force untuk mensorting A[0..n-1]
Brute Force Sorting
Brute Force Sorting
Selection Sort
Analisalah kompleksitas waktu selection sort Ө(n
2)
Selection Sort
Apa sorting itu?
A
0≤ A
1≤ A
2≤ … A
n-1≤ A
nAlternative Brute Force Sorting
Perhatikan bahwa setelah sorting :
A
0≤ A
1A
1≤ A
2A
2≤ A
3…
Bubble Sort
Algorithm bubbleSort(A[0..n-1])
//mensorting array A menggunakan bubble sort //input : array A[0..n-1]
//output : array A[0..n-1] dalam keadaan terurut naik for i ← 0 to n – 2 do
for j ← 0 to n – 2 – i do
if A[j + 1] < A[j] swap A[j] and A[j + 1]
Analisalah kompleksitas waktu bubble sort Ө(n
2)
Bubble Sort
Rarely a source of clever or efficeient algorithm BUT important algorithm design strategy
Applicable to a very wide variety of problems
Yields reasonable algorithms of at least some practical value with no limitation of instance size
Expense of designing a more efficient algorithm may be unjustifiable if only a new instances of a problem need to be solved and a brute force algorithm can solve those instances with acceptable speed