Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. It continues to do this until the list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list with each iteration. Though easy to understand, it's not efficient for large lists due to its O(n^2) time complexity.
//Bubble Sort Algorithm
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
Selection sort iterates through the array, selecting the smallest (or largest, depending on sorting order) element, and swapping it with the first unsorted element. This process continues until the entire array is sorted. It has a time complexity of O(n^2) in all cases, making it inefficient for large datasets but simple to implement. It's an in-place comparison-based sorting algorithm. It is not stable, meaning that the relative order of equal elements is not preserved.
//Selection Sort
function selection_sort(array):
m = length(array)
for i = 0 to m-2:
// Assume the current index (i) has the minimum value
min_index = i
// Find the minimum element in the remaining unsorted part
for j = i + 1 to m-1:
if array[j] < array[min_index]:
min_index = j
// Swap the found minimum element with the first element of the unsorted part
swap(array[i], array[min_index])