Download presentation
Presentation is loading. Please wait.
1
Alg2_1c Extra Material for Alg2_1
Algorithms part2 Alg2_1c Extra Material for Alg2_1
2
Bubble Sort Algorithm Define the entire array as the unsorted portion of the array. While the unsorted portion of the array has more than one element: 1. For every element in the unsorted portion, swap with the next neighbor if it is larger than the neighbor. 2. Reduce the size of the unsorted portion of the array by 1.
3
14 2 10 5 1 3 17 7
4
Bubble sort code public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
5
Bubble Sort – Algorithm Complexity
Time consuming operations compares, swaps. #Compares a for loop embedded inside a while loop (n-1)+(n-2)+(n-3) …+1 , or O(n2) #Swaps inside a conditional -> #swaps data dependent !! Best Case 0, or O(1) Worst Case (n-1)+(n-2)+(n-3) …+1 , or O(n2)
6
Remember: Sorting Algorithms
Insertion Sort O( n2 ) Selection Sort Bubble Sort
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.