Bubble Sort Algorithm
Bubble Sort Algorithm
In this algorithm, adjacent elements are compared one by one repeatedly and
swapped if they are in the wrong order. There are generally n-1 passes until all the
elements are in their correct places.
Some essential characteristics of the bubble sort algorithm are given here.
bubbleSort(arr)
n = length (arr);
for i from 0 to n-1:
swapped = false
for j from 0 to n-i-1:
if arr[j] > arr[j+1]:
swap(arr[j], arr[j+1])
swapped = true
if swapped is false:
break;
Insertion Sort Algorithm
Insertion sort divides the array into two different parts. They are sorted and unsorted
parts. It then compares the sorted parts and, after comparison, swaps them if
needed. It makes the final sorted array one at a time, at its correct position within the
sorted array.
insertionSort(arr):
n = length(arr)
for i from 1 to n-1
key = arr[i]
j=i–1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j=j–1
arr[j+1] = key
Selection Sort Algorithm
In selection sort, we need to ensure that the smallest element of the current unsorted
subarray goes to its final position which is done by finding the smallest element in
the subarray. This algorithm reduces the size of the unsorted part by 1 and increases
the size of the sorted part by 1 at each pass.
selectionSort(arr):
n = length(arr)
for i from 0 to n-1:
min_index = i
for j from i+1 to n-1:
if arr[j] < arr[min_index]:
min_index = j
swap(arr[i], arr[min_index])
Quick Sort Algorithm
The worst scenario takes place in a quick sort when the array is already
sorted.
The time complexity of the quick sort algorithm is O (n^2).
It is also a recursive algorithm.
It also follows the divide-and-conquer approach.
It works by selecting a pivot element and then partitioning the array into two
major parts.
Quick Sort Algorithm
i = low – 1
i=i+1
swap(arr[i], arr[j])
return i + 1
Merge Sort