CS 1371 Lecture Notes - Lecture 19: Bubble Sort, Quicksort

69 views5 pages

Document Summary

1) start at first element, compare to second element. Swap if second element is less than the first element. 2) continue down the line comparing adjacent elements, swapping if necessary. 3) after 1 pass, the greatest value is guaranteed to be at the last spot. 4) after n passes, the vector will be sorted. Sample code: function vec = bubblesort(vec) n = length(vec); for j=1:n-1 for i=1:n-1 %n-1 because we are comparing adjacent elements if vec(i)>vec(i+1); %swap elements that are out of order temp=vec(i); %must use temp so next line does not override a(i) vec(i)=vec(i+1); vec(i+1)=temp; end end end end. 1) assume the first element is sorted (start at the second element) 2) for each element in the vector: i) grab the element and call it your current. ii) move all values greater than current to the right to make room for current iii) insert current in the correct position.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents