3rd Lecture BSCS6 of Algorithm (Sorting, Bubble Sorting and Analysis of Bubble Sorting) - 31-08
3rd Lecture BSCS6 of Algorithm (Sorting, Bubble Sorting and Analysis of Bubble Sorting) - 31-08
Sorting Algorithms
What is sorting?
Bubble sort and analysis of bubble sort
What is Sorting?
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order. This algorithm
is not suitable for large data sets as its average and worst-case time
complexity is quite high.
Second Pass:
Place the second largest element at correct position
Bubble Sort Algorithm : Placing the second largest element at correct
position
Third Pass:
Place the remaining two elements at their correct positions.
positions
Algorithm
In the algorithm given below, suppose arr is an array of n elements. The
assumed swap function in the algorithm will swap the values of given array
elements.
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort
Now, let's see the time complexity of bubble sort in the best case, average case,
and worst case. We will also see the space complexity of bubble sort.
1. Time Complexity
Case Time Complexity
2. Space Complexity
Space Complexity O(1)
Stable YES