Bubble Selection Sort
Bubble Selection Sort
begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort
Bubble sort Algorithm
# Bubble sort in Python
Outer for loop i=0 to 4
def bubbleSort(array): first pass : i=0 ,
j=0,
# loop to access each array element
j=1, 4 comparisons
for i in range(len(array)):
j=2,
# loop to compare array elements j=3
for j in range(0, len(array) - i - 1): Second pass : i=1 ,
j=0,
# compare two adjacent elements j=1,
# change > to < to sort in descending order j=2, 3 comparisons
if array[j] > array[j + 1]:
Third pass : i=2 , j=0,
# swapping elements if elements
# are not in the intended order j=1, 2 comparisons
temp = array[j]
array[j] = array[j+1] Fourth pass : i=3 , j=0,
array[j+1] = temp 1 comparisons
data = [2, 45, 0, 11, 9] or data = array.array('i',[5,88,99,22]) Fifth pass : i=4 , j=0,
0 comparisons
bubbleSort(data)
The complexity of selection sort is O(n2), where n is the number of items. Due to this, it is not suitable for
large data sets.
Space complexity – O(1)
1.SELECTION SORT(arr, n)
2.
3.Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4.Step 2: CALL SMALLEST(arr, i, n, pos)
5.Step 3: SWAP arr[i] with arr[pos]
6.[END OF LOOP]
7.Step 4: EXIT
8.
9.SMALLEST (arr, i, n, pos)
10.Step 1: [INITIALIZE] SET SMALL = arr[i]
11.Step 2: [INITIALIZE] SET pos = i
12.Step 3: Repeat for j = i+1 to n
13.if (SMALL > arr[j])
14. SET SMALL = arr[j]
15.SET pos = j
16.[END OF if]
17.[END OF LOOP]
18.Step 4: RETURN pos
# Selection sort in Python
# time complexity O(n*n)
#sorting by finding min_index
def selectionSort(array, size):
Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is the
smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the
array that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in
the sorted array. So, after two iterations, the two smallest values are placed at the
beginning in a sorted way.
The same process is applied to the rest of the array elements.
Now, we are showing a pictorial representation of the entire sorting process.