We talk about some sorting algorithms like bubble sort, selection sort, insertion sort and merge sort.
BUBBLE SORT:
Bubble sort is a sorting method. In this we compare two elements and swap them if they are in wrong order. This process repeats again and again until the array becomes sorted.
Example:
[5, 1, 4, 2]
In this array we use two for loops and search like fix one element in first for loop with that compare to the next elements in next for loop until it sorted or the first for loop reaches its end by using this we compare and sort with every possible pairs in that array.
TIME COMPLEXITY:
Time complexity is O(n²) because we use nested loops.
SELECTION SORT:
Selection sort works by selecting minimum element in the array . It finds the smallest element from unsorted part then swaps the element from the beginning of the unsorted array.
Example:
[5, 4, 2, 1]
In this it takes 1 because 1 is smallest then it swaps it with first element of unsorted array 5 and then take 2 and swaps with 4 like that it sort the array until it sorted. for searching the smallest element in the array I can use binary search because its more efficient then linear.
TIME COMPLEXITY:
Time complexity is O(n²) because it uses nested loop.
INSERTION SORT:
Insertion sort is a sorting algorithm that takes the element from the starting of the array then inserts into correct position of the array.
Example:
[5, 2, 4, 6, 1, 3]
first it takes two then compare with left side element is it lesser then it swifts like [2,5,4,6,1,3] then take the next element 4 then move to the left side of array and compare with elements then it goes to the correct position in it and then it takes 6 it compare with all elements in left but all of them are lower then it so it didn't inserted on left side of array it remains same
It is continued until it reaches the end of the array once it reaches end of the array it already sorted.
TIME COMPLEXITY:
Compared to other two sorts its more efficiency.
Top comments (0)