1 / 3

Bubble sort (LList,n)

Bubble sort (LList,n). not_sorted  true; while not_sorted do not_sorted  false ; cur  LList.first; while cur.next  NIL do if cur.data> cur.next.data then swap(cur.data,cur.next.data); not_sorted  true; cur  cur.next;. Bubble sort (LList,n). for i=1 to n-1 do

linda-bates
Download Presentation

Bubble sort (LList,n)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Bubble sort (LList,n) not_sorted  true; while not_sorted do not_sorted  false; cur  LList.first; while cur.next  NIL do if cur.data> cur.next.data then swap(cur.data,cur.next.data); not_sorted  true; cur  cur.next;

  2. Bubble sort (LList,n) • for i=1 to n-1 do • cur  LList.first; • for j=1 to n-i do • if cur.data> cur.next.data then • swap (cur.data, cur.next.data); • cur  cur.next; Invariant 1: j<n, l j, after j iterations of the for-loop at line 3, (j+1)-st el  l-th Invariant 2:i<n, after i iterations of thefor-loopat line 1, the last i el’s are “in place” Proof: by induction using Inv.1 Corollary: When i=n-1 all elements are “in place” (sorted) • Proof by induction on j: • Base: j=0 trivial; j=1 obvious. • IH: suppose true for j–1: j-th el is max in [1..j] • IS: after the next iteration of 3-5, (j+1) is the max

  3. Insertion Sort for i= 2 to n doj  i;while j>1 AND A[j-1]>A[j] do swap( A[j], A[j-1] ) j  j-1 Invariant: at the end of each for-loop iteration the first i elements are in the sorted order

More Related