Lecture18 - Bubble Sort and Quick-sort EECS 233-2- Previous...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Bubble Sort and Quick-sort EECS 233-2- Previous Lecture Method 1: Selection Sort For each position of an array, nd the element for it O(n 2 ) comparisons, O(n) moves Method 2: Insertion Sort For each element, nd a position to insert it O(n 2 ) comparisons, O(n 2 ) moves O(n) if the array is sorted or nearly sorted Method 3: Shell Sort Based on the observation that insertion sort requires O(n) running time for sorted or nearly sorted array Generalization of insertion sort with larger jumps, using strides larger than 1 (for insertion sort, the stride = 1) Use a decreasing sequence of strides-3- Method 4: Bubble Sort Perform a sequence of passes through the array. On each pass: proceed from left to right, swapping adjacent elements if they are out of order. Larger elements bubble up to the end of the array. At the end of the kth pass, the k rightmost elements are in their Fnal positions. Example: After one pass After two passes After three passes-4- Implementation of Bubble Sort static void bubbleSort(int arr, int n) { for (int i = n 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j+1]) swap(arr, j, j+1); } } } The inner loop performs a single pass The outer loop governs the number of passes, and the ending point of each pass-5- Running Time Analysis static void bubbleSort(int arr, int n) { for (int i = n 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j+1]) swap(arr, j, j+1); } } } Number of comparisons the k-th pass performs ? comparisons, k=1,2,,n-1 so we get C(n) = ? Moves: depends on the contents of the array in the worst case: the array is in reverse order, and every comparison leads to a swap (3 moves), so M(n) = ?...
View Full Document

Page1 / 20

Lecture18 - Bubble Sort and Quick-sort EECS 233-2- Previous...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online