קורס מחשב לרפואנים 274121 הרצאה 8: סיבוכיות ומיון ראובן בר-יהודה. © כל הזכויות שמורות לטכניון – מכון טכנולוגי לישראל.

Slides:



Advertisements
Similar presentations
Arrays (Continue) Sorting and searching. outlines Sorting – Bubble sort Linear search – min and max Binary search.
Advertisements

Bubble Sort Example 9, 6, 2, 12, 11, 9, 3, 7 6, 9, 2, 12, 11, 9, 3, 7 Bubblesort compares the numbers in pairs from left to right exchanging.
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Bubble Sort Algorithm It is so named because numbers (or letters) which are in the wrong place “bubble-up” to their correct positions (like fizzy lemonade)
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Selection and Insertion Sort Mrs. C. Furman October 1, 2008.
Visual C++ Programming: Concepts and Projects
CSE 373: Data Structures and Algorithms
Simple Sorting Algorithms
Bubble Sort Notes David Beard CS181. Bubble Sort for Strings Double pass algorithm to sort a single dimensional array. Inner loop “bubbles” largest element.
Overview Sort – placing data in an array in some order (usually decreasing or increasing order) Bubble Sort More efficient bubble sort.
Bubble Sort Merge Sort. Bubble Sort Sorting Sorting takes an unordered collection and makes it an ordered one
C++ Plus Data Structures
Algorithm Efficiency and Sorting
Sorting Algorithms Bubble Sort Merge Sort Quick Sort Randomized Quick Sort.
Sorting 2 An array a is sorted (ascending order) if: for all i a[i]  a[j] Probably the most well-studied algorithmic problem in Computer Science There.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
COMP102 Lab 131 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Bubble Sort Merge Sort. Bubble Sort Sorting Sorting takes an unordered collection and makes it an ordered one
Analysis of Bubble Sort and Loop Invariant
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Bubble Sort. Bubble Sort Example 9, 6, 2, 12, 11, 9, 3, 7 6, 9, 2, 12, 11, 9, 3, 7 6, 2, 9, 12, 11, 9, 3, 7 6, 2, 9, 11, 12, 9, 3, 7 6, 2, 9, 11, 9, 12,
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
Lecture -3 on Data structures Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Array Data structures are classified as either linear or nonlinear.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Sorting: Optimising Bubblesort Damian Gordon. Sorting: Bubble Sort If we look at the bubble sort algorithm again:
Sorting Techniques Rizwan Rehman Centre for Computer Studies Dibrugarh University.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Bubble Sort.
Python: Sorting - Bubblesort Damian Gordon. Sorting: Bubblesort The simplest algorithm for sort an array is called BUBBLE SORT. It works as follows for.
1 Sorting (Bubble Sort, Insertion Sort, Selection Sort)
Bubble Sort Example
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
SORTING ALGORITHMS King Saud University College of Applied studies and Community Service CSC 1101 By: Nada Alhirabi 1.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Sorting Sorting takes an unordered array and makes it an ordered one
Elementary Sorting 30 January Simple Sort // List is an array of size == n for (i = 1; i < n; i++) for (j = i+1; j List[j])
Insertion Sort while some elements unsorted: Using linear search, find the location in the sorted portion where the 1 st element of the unsorted portion.
CS1022 Computer Programming & Principles Lecture 2.2 Algorithms.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Searching and Sorting Searching algorithms with simple arrays
Sort Algorithm.
The Bubble Sort Mr. Dave Clausen La Cañada High School
CS212: Data Structures and Algorithms
Sorting.
Recitation 13 Searching and Sorting.
3.3 Fundamentals of data representation
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Linear and Binary Search
Sorting Algorithms IT12112 Lecture 07.
Analysis of Bubble Sort and Loop Invariant
Sorting Algorithms Ellysa N. Kosinaya.
Lecture 16 Bubble Sort Merge Sort.
Bubble Sort Example 9, 6, 2, 12, 11, 9, 3, 7 6, 9, 2, 12, 11, 9, 3, 7 Bubblesort compares the numbers in pairs from left to right exchanging.
Visit for More Learning Resources
Sorting Example Bubble Sort
Discrete Mathematics CS 2610
Module 8 – Searching & Sorting Algorithms
Visit for more Learning Resources
Presentation transcript:

קורס מחשב לרפואנים הרצאה 8: סיבוכיות ומיון ראובן בר-יהודה. © כל הזכויות שמורות לטכניון – מכון טכנולוגי לישראל

משאבי זמן וזיכרון של תוכניות מחשב 2 אלו מתתי התוכניות הבאות צורכת יותר זמן? הנחה: כל פעולה עולה 1 יחידות זמן. עבור n=0 5 פעולות כל איטרציה מוסיפה 5 פעולות Time(n) = 5 + 5*n עבור n=0 4 פעולות כל איטרציה מוסיפה 3 פעולות סך מספר האיטרציות הוא n 2 Time(n) = 4 + 3*n 2 1. y = 0; 2. i = ; 3. while i < n 4. i=i+1; 5. y = y + i; 6. end 1. i = n*n; 2. y = 0; 3. while i >0 4. i = i - 1; 5. end

משאבי זמן וזיכרון של תוכניות מחשב 3 >> n=0:10; >> plot(n,5+5*n,n,4+3*n.^2) >> xlabel('n') >> ylabel('time')

משאבי זמן וזיכרון של תוכניות מחשב 4 אמנם עבור n-ים קטנים הפרבולה מתחת לישר אבל עבור n-ים גדולים הפרבולה גבוהה יותר. מה שמעניין אותנו הם סדרי הגודל: התוכנית הראשונה צורכת זמן בסדר גודל לינארי התוכנית השנייה צורכת זמן בסדר גודל ריבועי שאלה: נניח שעבור n מסויים התוכנית הראשונה תצרוך זמן ריצה של דקה, מה יקרה אם נכפיל את גודלו של nב 1000 ? שאלה: נניח שעבור n מסויים התוכנית השנייה תצרוך זמן ריצה של דקה, מה יקרה אם נכפיל את גודלו של nב 1000 ? לינארי ריבועי

משאבי זמן וזיכרון של תוכניות מחשב (סיבוכיות) 5 דוגמאות לסדרי גודל קבוע: (מסומן ב-(O(1): 1, 10, , לינארי (מסומן ב-(O(n) : 5 + 5*n, 5n+1999, 0.001n , n+n 0.7 ריבועי (מסומן ב-(O(n 2 ) : 5 + 5*n 2, 5n+1999+n 2, 0.001n , 1+2+…+n פולינומי: (מסומן ב poly(n) או (n O(1): 5 + 5*n 11, 5n+1999+n 12, 0.001n , לוגריתמי (מסומן ב-((O(log(n) : 5 + 5*log(n), log(1+2+3+…+n), log 22 (n) ובלתי נסבל: אקספוננציאלי:, 1.1 3n+2,2 n שאלה: נניח שעבור n מסויים התוכנית האקספוננציאלית תצרוך זמן ריצה של שניה אחת, מה יקרה אם נגדיל את גודלו של nב 100 ? תשובה: שניות > שניות > שעות > שנים

6 דוגמאות לסדרי גודל קבוע: (מסומן ב-(O(1): 1, 10, , לינארי (מסומן ב-(O(n) : 5 + 5*n, 5n+1999, 0.001n , n+n 0.7 ריבועי (מסומן ב-(O(n 2 ) : 5 + 5*n 2, 5n+1999+n 2, 0.001n , 1+2+…+n פולינומי: (מסומן ב poly(n) או (n O(1): 5 + 5*n 11, 5n+1999+n 12, 0.001n , לוגריתמי (מסומן ב-((O(log(n) : 5 + 5*log(n), log(1+2+3+…+n), log 22 (n) ובלתי נסבל: אקספוננציאלי:, 1.1 3n+2,2 n שאלה: נניח שעבור n מסויים התוכנית הלוגריתמית תצרוך זמן ריצה של דקה אחת, מה יקרה אם נגדיל את גודלו של nפי ? תשובה: הזמן הקודם t=log(n) הזמן החדש t >log(n) +log( ) =log( n) שזה טיפ טיפה יותר מדקה. כלומר זניח. משאבי זמן וזיכרון של תוכניות מחשב (סיבוכיות)

סיבוכיות זמן ומקום כתוב פונקציה שמחשבת סכום מערך חד מימדי (ללא שימוש ב sum ) 7 1.function y = my_sum(x) 2. y = 0; n = length(x); 3. for i = 1:n 4. y = y + x(i); 5. end סיבוכיות זמן: כל איטרציה דורשת זמן קבוע, לכן סיבוכיות הזמן היא לינארית, כלומר.o(n) סיבוכיות זכרון נוסף: המערך x, לא משוכפל בגלל שהפונקציה לא משנה את ערכו. מלבד המערך x, יש לנו צורך במערך 1:n, ולכן הזכרון הנוסף הוא לינארי. אפשר להגיע לזכרון קבוע ע"י ריצה ישירה על איברי המערך x 1.function y = my_sum(x) 2. y = 0; 3. for next = x 4. y = y + next; 5. end

מה סיבוכיות זמן/זכרון של תתי התוכניות הבאות: 8 משאבי זמן וזיכרון של תוכניות מחשב (סיבוכיות) a = 1:n; max(a); קריאה לפונקציה min(a(2:n)) קריאה לפונקציה sum(n:n^2)

Sorting Sorting takes an unordered collection and makes it an ordered one

מיונים שנלמד מיון בזמן ריבועי – היום: מיון ע"י מקסימום מיון בועות – Bubble Sort מיון בזמן לינארי (של ציונים) – היום מיון דליים – Bucket sort מיונים יעילים (בזמן O(nlogn)) – בעוד כשבועיים Quick Sort Merge Sort 10

Sort by max: time complexity O(n 2 ) 1.function a = sort_by_max( a ) 2.% sort members of array in non decreasing order 3. for top = length(a):-1:1 % at this point all members above index “top” are in their proper location 4. i = index_of_max(a,top); %swap a(i) with a(top) 7. temp = a(i); a(i) = a(top); a(top) = temp; 8. end 9.end function i_max = index_of_max( a, n ) 12.% find the index of the maximum member among a(1:n) 13. i_max = 1; 14. for i = 2:n % invariant: at this point a(i_max) = MAXIMUM{a(1), a(2)…a(i-1)} 15. if a(i) > a(i_max) 16. i_max = i; 17. end 18. end 19.end 11

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping Swap

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping Swap

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping Swap

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping No need to swap

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping Swap

"Bubbling Up" the Largest Element Traverse a collection of elements –Move from the front to the end –“Bubble” the largest value to the end using pair-wise comparisons and swapping Largest value correctly placed

The “Bubble Up” Algorithm 1.for index = 1:top-1 2.%Invariant: a(index) is maximum among a(1:index) 3. if a(index)>a(index+1) 4. a([index,index+1]) = a([index+1,index]); 5. end 6.end * top=5 6

Items of Interest Notice that only the largest value is correctly placed All other values are still out of order So we need to repeat this process Largest value correctly placed top=5 6

Repeat “Bubble Up” How Many Times? If we have N elements… And if each time we bubble an element, we place it in its correct location… Then we repeat the “bubble up” process N – 1 times. This guarantees we’ll correctly place all N elements.

“Bubbling” All the Elements N - 1

Reducing the Number of Comparisons

On the N th “bubble up”, we only need to do MAX-N comparisons. For example: –This is the 4 th “bubble up” –MAX-N is 6 –Thus we have 2 comparisons to do Reducing the Number of Comparisons

Already Sorted Collections? What if the collection was already sorted? What if only a few elements were out of place and after a couple of “bubble ups,” the collection was sorted? We want to be able to detect this and “stop early”!

Using a Boolean “Flag” We can use a boolean variable to determine if any swapping occurred during the “bubble up.” If no swapping occurred, then we know that the collection is already sorted! This boolean “flag” needs to be reset after each “bubble up.”

Putting It All Together

1.function a = bubble_sort( a ) 2. n = length(a); 3. for top = n-1:-1:1 4. % all above top+1 are placed in their final position 5. did_swap = false; 6. for index = 1:top 7. %disp(a) 8. if a(index)>a(index+1) 9. a([index,index+1]) = a([index+1,index]); 10. did_swap = true; 11. end 12. end 13. if ~did_swap 14. return 15. end 16. end 17.end Inner loop Bubble up Outer loop Bubble_sort.m

An Animated Example to_do index 7 N 8 did_swap true

An Animated Example to_do index 7 1 N 8 did_swap false

An Animated Example to_do index 7 1 N 8 Swap did_swap false

An Animated Example to_do index 7 1 N 8 Swap did_swap true

An Animated Example to_do index 7 2 N 8 did_swap true

An Animated Example to_do index 7 2 N 8 Swap did_swap true

An Animated Example to_do index 7 2 N 8 Swap did_swap true

An Animated Example to_do index 7 3 N 8 did_swap true

An Animated Example to_do index 7 3 N 8 Swap did_swap true

An Animated Example to_do index 7 3 N 8 Swap did_swap true

An Animated Example to_do index 7 4 N 8 did_swap true

An Animated Example to_do index 7 4 N 8 Swap did_swap true

An Animated Example to_do index 7 4 N 8 Swap did_swap true

An Animated Example to_do index 7 5 N 8 did_swap true

An Animated Example to_do index 7 5 N 8 Swap did_swap true

An Animated Example to_do index 7 5 N 8 Swap did_swap true

An Animated Example to_do index 7 6 N 8 did_swap true

An Animated Example to_do index 7 6 N 8 Swap did_swap true

An Animated Example to_do index 7 6 N 8 Swap did_swap true

An Animated Example to_do index 7 7 N 8 did_swap true

An Animated Example to_do index 7 7 N 8 Swap did_swap true

An Animated Example to_do index 7 7 N 8 Swap did_swap true

After First Pass of Outer Loop to_do index 7 8 N 8 Finished first “Bubble Up” did_swap true

The Second “Bubble Up” to_do index 6 1 N 8 did_swap false

The Second “Bubble Up” to_do index 6 1 N 8 did_swap false No Swap

The Second “Bubble Up” to_do index 6 2 N 8 did_swap false

The Second “Bubble Up” to_do index 6 2 N 8 did_swap false Swap

The Second “Bubble Up” to_do index 6 2 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 3 N 8 did_swap true

The Second “Bubble Up” to_do index 6 3 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 3 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 4 N 8 did_swap true

The Second “Bubble Up” to_do index 6 4 N 8 did_swap true No Swap

The Second “Bubble Up” to_do index 6 5 N 8 did_swap true

The Second “Bubble Up” to_do index 6 5 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 5 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 6 N 8 did_swap true

The Second “Bubble Up” to_do index 6 6 N 8 did_swap true Swap

The Second “Bubble Up” to_do index 6 6 N 8 did_swap true Swap

After Second Pass of Outer Loop to_do index 6 7 N 8 did_swap true Finished second “Bubble Up”

The Third “Bubble Up” to_do index 5 1 N 8 did_swap false

The Third “Bubble Up” to_do index 5 1 N 8 did_swap false Swap

The Third “Bubble Up” to_do index 5 1 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 2 N 8 did_swap true

The Third “Bubble Up” to_do index 5 2 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 2 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 3 N 8 did_swap true

The Third “Bubble Up” to_do index 5 3 N 8 did_swap true No Swap

The Third “Bubble Up” to_do index 5 4 N 8 did_swap true

The Third “Bubble Up” to_do index 5 4 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 4 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 5 N 8 did_swap true

The Third “Bubble Up” to_do index 5 5 N 8 did_swap true Swap

The Third “Bubble Up” to_do index 5 5 N 8 did_swap true Swap

After Third Pass of Outer Loop to_do index 5 6 N 8 did_swap true Finished third “Bubble Up”

The Fourth “Bubble Up” to_do index 4 1 N 8 did_swap false

The Fourth “Bubble Up” to_do index 4 1 N 8 did_swap false Swap

The Fourth “Bubble Up” to_do index 4 1 N 8 did_swap true Swap

The Fourth “Bubble Up” to_do index 4 2 N 8 did_swap true

The Fourth “Bubble Up” to_do index 4 2 N 8 did_swap true No Swap

The Fourth “Bubble Up” to_do index 4 3 N 8 did_swap true

The Fourth “Bubble Up” to_do index 4 3 N 8 did_swap true No Swap

The Fourth “Bubble Up” to_do index 4 4 N 8 did_swap true

The Fourth “Bubble Up” to_do index 4 4 N 8 did_swap true No Swap

After Fourth Pass of Outer Loop to_do index 4 5 N 8 did_swap true Finished fourth “Bubble Up”

The Fifth “Bubble Up” to_do index 3 1 N 8 did_swap false

The Fifth “Bubble Up” to_do index 3 1 N 8 did_swap false No Swap

The Fifth “Bubble Up” to_do index 3 2 N 8 did_swap false

The Fifth “Bubble Up” to_do index 3 2 N 8 did_swap false No Swap

The Fifth “Bubble Up” to_do index 3 3 N 8 did_swap false

The Fifth “Bubble Up” to_do index 3 3 N 8 did_swap false No Swap

After Fifth Pass of Outer Loop to_do index 3 4 N 8 did_swap false Finished fifth “Bubble Up”

Finished “Early” to_do index 3 4 N 8 did_swap false We didn’t do any swapping, so all of the other elements must be correctly placed. We can “skip” the last two passes of the outer loop

Summary “Bubble Up” algorithm will move largest value to its correct location (to the right) Repeat “Bubble Up” until all elements are correctly placed: –Maximum of N-1 times –Can finish early if no swapping occurs We reduce the number of elements we compare each time one is correctly placed

Truth in CS Act NOBODY EVER USES BUBBLE SORT NOBODY NOT EVER BECAUSE IT IS EXTREMELY INEFFICIENT

בדיקת זמנים... >> a = rand(1,5000); >> b = a; >> tic >> b = bubble_sort(a); >> toc Elapsed time is seconds. >> tic >> b = sort(a); >> toc Elapsed time is seconds. >> 104

קישורים - Bubble_sortBubble_sort ויקיפדיה ריקוד אנימציה ביו-טיוב מצגת 105

מיון דליים: תכנית שממיינת מערך ציונים בזמן לינארי 1.function y = bucket_sort( x ) 2.h = zeros(1,101); % h(i) is the number of students with grade of i-1 3.for i = x+1 4. h(i) = h(i)+1; 5.end 6.k = 0; y = zeros(1,length(x)); 7.for i = 1: for j = 1:h(i) 9. k = k + 1; 10. y(k) = i - 1; 11. end 12.end 106