Practical No. 4 Sorting Algorithms_ Implement sorting algorithms (e.g., bubble, selection, insertion).
Practical No. 4 Sorting Algorithms_ Implement sorting algorithms (e.g., bubble, selection, insertion).
4
Sorting Algorithms: Implement sorting algorithms (e.g., bubble, selection,
insertion).
Bubble Sort: Compares adjacent elements and swaps if needed. Repeats until
the array is sorted. Easy to understand but slow for large datasets.
Selection Sort: Finds the smallest element in the unsorted part and swaps it with
the current position. Simple but not efficient for large arrays.
Insertion Sort: Inserts each element into its correct position within the sorted
part of the array. Faster for nearly sorted data.
1. Bubble Sort:
○ Repeatedly compares adjacent elements and swaps them if they are
in the wrong order.
○ Time Complexity: O(n2)O(n^2)O(n2) in the worst and average case.
○ Space Complexity: O(1)O(1)O(1) (in-place sorting).
2. Selection Sort:
○ Divides the list into a sorted and unsorted section, repeatedly selects
the smallest element from the unsorted section, and moves it to the
sorted section.
○ Time Complexity: O(n2)O(n^2)O(n2) for all cases.
○ Space Complexity: O(1)O(1)O(1).
3. Insertion Sort:
○ Builds the sorted array one element at a time by comparing the
current element to the already sorted section and inserting it in its
correct position.
○ Time Complexity: O(n2)O(n^2)O(n2) in the worst case;
O(n)O(n)O(n) in the best case (already sorted input).
○ Space Complexity: O(1)O(1)O(1).
Code: