31251 Lecture Notes - Lecture 7: Merge Sort, Quicksort, Sorting Algorithm

54 views4 pages
Sorting
Bubble Sort
bubbleSort(int a[]) {
//assume array is length n
bool swapHappened;
do {
swapHappened = false;
for (int i = 0; i < n; i++){
if (a[i] > a[i+1]){
swap(a[i], a[i+1]);
swapHappened = true;
}
}
} while (swapHappened);
}
Easy to code.
Bad at almost everything else.
Best case time: O(n), Average case: O(n 2 ), Worst case: O(n 2 ).
Only O(1) extra space need though!
Insertion Sort
insertionSort(int a[]){
for (int i = 1; i < n; i++){
int x = a[i];
int pos = i-1;
while (pos >= 0 && a[pos] > x){
a[pos + 1] = a[pos];
pos--;
}
a[pos + 1] = x;
}
}
1 | P a g e
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

Already have an account? Log in

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