What is Sorting?
Sorting is the process of rearranging a given array or list of elements according to a comparison operator. This operator is used to determine the new order of elements, typically arranging them in ascending or descending order.
Sorting Terminology
- In-place Sorting: Uses constant space to sort the elements by modifying the original array (e.g., Selection Sort, Bubble Sort, Insertion Sort, Heap Sort).
- Internal Sorting: All data is placed in main memory during sorting (e.g., Heap Sort, Bubble Sort, Selection Sort, Quick Sort, Shell Sort, Insertion Sort).
- External Sorting: Used for sorting massive amounts of data that cannot fit into memory at once (e.g., Merge Sort, Polyphase Sort).
- Stable Sorting: Maintains the relative order of equal elements (e.g., Merge Sort, Insertion Sort, Bubble Sort).
- Unstable Sorting: May change the relative order of equal elements (e.g., Quick Sort, Heap Sort, Shell Sort).
Characteristics of Sorting
- Time Complexity: Measures how long an algorithm takes to run. Includes worst-case, average-case, and best-case performance.
- Space Complexity: Amount of memory required to execute the algorithm.
- Stability: Preserves the relative order of equal elements after sorting.
- In-Place Sorting: Requires no additional memory beyond the original array.
- Adaptivity: Improves performance by taking advantage of pre-existing order in the data.
Applications of Sorting
Algorithms play a crucial role in various fields and have many applications, including:
- Searching Algorithms: Crucial for search algorithms like binary search, where data must be sorted beforehand.
- Data Management: Easier to search, retrieve, and analyze sorted data.
- Database Optimization: Improves query performance in databases.
- Machine Learning: Prepares data for training machine learning models.
- Data Analysis: Helps identify patterns, trends, and outliers in datasets.
- Operating Systems: Used for tasks like task scheduling, memory management, and file system organization.
Types of Sorting Algorithms
Comparison-based Sorting Algorithms: These algorithms sort data by comparing elements. Examples include:
- Selection Sort
- Bubble Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
Non-Comparison-based Sorting Algorithms: These algorithms sort data without comparing elements. Examples include:
- Counting Sort
- Radix Sort
- Bucket Sort
Comparison-based Sorting Algorithms:
Selection Sort: Simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.
Bubble Sort: The simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
Insertion Sort: Simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.
Merge Sort: Sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array.
Quick Sort: Sorting algorithm based on the Divide and Conquer algorithm that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.
Heap Sort: Comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
Non-Comparison-based Sorting Algorithms:
Counting Sort: Is efficient for small ranges of input values, counting frequencies to determine correct positions for sorting.
Radix Sort: Linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys.
Bucket Sort: Involves distributing elements into uniformly sized buckets, sorting each bucket individually using another sorting algorithm, and finally merging the sorted buckets to achieve a fully sorted array.
Selection Sort
Simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.
Step-by-Step Execution:
Initial Array: [64, 25, 12, 22, 11]
First pass:
- Find the minimum element in the remaining unsorted array [64, 25, 12, 22, 11], which is 11.
- Swap this minimum element with the first element (64).
- Array after first pass: [11, 25, 12, 22, 64]
Second Pass:
- Find the minimum element in the remaining unsorted array [25, 12, 22, 64], which is 12.
- Swap this minimum element with the second element (25).
- Array after second pass: [11, 12, 25, 22, 64]
Third Pass:
- Find the minimum element in the remaining unsorted array [25, 22, 64], which is 22.
- Swap this minimum element with the third element (25).
- Array after third pass: [11, 12, 22, 25, 64]
Fourth Pass:
- Find the minimum element in the remaining unsorted array [25, 64], which is 25.
- Swap this minimum element with the fourth element (25).
- Array after fourth pass: [11, 12, 22, 25, 64]
Fifth Pass:
- Find the minimum element in the remaining unsorted array [64], which is 64.
- No swap needed as 64 is already in the fifth position.
- Array after fifth pass: [11, 12, 22, 25, 64]
Sorted Array:
After the fifth pass, the array is sorted: [11, 12, 22, 25, 64]
Below is the implementation of the above approach:
#include
using namespace std;
// Function for Selection sort
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of
// unsorted subarray
for (i = 0; i < n - 1; i++) {
// Find the minimum element in
// unsorted array
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
// Swap the found minimum element
// with the first element
if (min_idx != i)
swap(arr[min_idx], arr[i]);
}
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++) {
cout << arr[i] << " ";
cout << endl;
}
}
// Driver program
int main()
{
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
Output:
Sorted array: 11 12 22 25 64
Complexity:
- Time Complexity: O(n2) in the worst and average cases.
- Auxiliary Space: O(1).
Advantages:
- Simple and easy to implement.
- Works well with small datasets.
- Requires minimal additional memory space (O(1) space complexity).
Disadvantages:
- Inefficient for large datasets due to its O(n2) time complexity.
- Not stable; does not preserve the relative order of elements with equal keys.
- Performs a large number of swaps compared to other sorting algorithms.
Bubble Sort
The simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
Step-by-Step Explanation of Bubble Sort:
Initial Array: arr[] = {6, 0, 3, 5}
First Pass:
- Compare arr[0] and arr[1]: 6 > 0, so swap them.
- Array after first comparison: arr[] = {0, 6, 3, 5}
- Compare arr[1] and arr[2]: 6 > 3, so swap them.
- Array after second comparison: arr[] = {0, 3, 6, 5}
- Compare arr[2] and arr[3]: 6 > 5, so swap them.
- Array after third comparison: arr[] = {0, 3, 5, 6}
After the first pass, the largest element (6) is placed at the correct position (end of the array).
Second Pass:
- Compare arr[0] and arr[1]: No swap needed (0 < 3).
- Compare arr[1] and arr[2]: No swap needed (3 < 5).
- Compare arr[2] and arr[3]: No swap needed (5 < 6).
After the second pass, the second largest element (5) is placed in its correct position just before the largest element (6).
Third Pass:
- Compare arr[0] and arr[1]: No swap needed (0 < 3).
- Compare arr[1] and arr[2]: No swap needed (3 < 5).
- Compare arr[2] and arr[3]: No swap needed (5 < 6).
After the third pass, the array is already sorted. No swaps are needed because the array is already in ascending order.
Summary:
Total Number of Passes: Bubble Sort requires 3 passes to sort the array of 4 elements (n - 1 passes where n is the number of elements).
Total Number of Comparisons:In the worst case, Bubble Sort makes n*(n-1)/2 comparisons , for n=4 gives 6 comparisons
Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. It passes through the list multiple times until the array is sorted.
Below is the implementation of the above approach:
#include
using namespace std;
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
// If no two elements were swapped
// by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << " " << arr[i];
}
// Driver program to test above functions
int main()
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: \n";
printArray(arr, N);
return 0;
}
Output:
Sorted array: 11 12 22 25 34 64 90
Complexity:
- Time Complexity: O(N^2)
- Auxiliary Space: O(1)
Advantages:
- Easy to understand and implement.
- Requires no additional memory space.
- Stable sorting algorithm (maintains relative order of elements with equal keys).
Disadvantages:
- Very slow for large datasets due to its O(N^2) time complexity.
- Comparison-based, which can limit efficiency in certain cases.