Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
A sorting algorithm that slightly improves on selection sort?
Two-way selection sort is an improved version of selection sort that processes the array from both ends simultaneously. Instead of finding only the minimum element in each pass, it finds both the minimum and maximum elements and places them at their correct positions from the left and right ends respectively.
Syntax
void twoWaySelectionSort(int arr[], int n);
Algorithm
begin
for i := 0, and j := n-1, increase i by 1, and decrease j by 1, until i >= j, do
min := minimum element from index i to j
max := maximum element from index i to j
i_min := index of min
i_max := index of max
exchange the arr[i] and arr[i_min]
if arr[i_min] is same as max, then
swap arr[j] and arr[i_min]
else
swap arr[j] and arr[i_max]
end if
done
end
Example
Here's a complete implementation of two-way selection sort in C −
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void twoWaySelectionSort(int arr[], int n) {
/* i will move from left, and j will move from right */
for (int i = 0, j = n - 1; i < j; i++, j--) {
int min = arr[i], max = arr[i];
int i_min = i, i_max = i; /* i_min and i_max will hold min and max index respectively */
for (int k = i; k <= j; k++) {
if (arr[k] > max) {
max = arr[k];
i_max = k;
} else if (arr[k] < min) {
min = arr[k];
i_min = k;
}
}
swap(&arr[i], &arr[i_min]); /* put the min into the index i */
if (arr[i_min] == max)
swap(&arr[j], &arr[i_min]);
else
swap(&arr[j], &arr[i_max]);
}
}
int main() {
int arr[] = {25, 45, 14, 10, 23, 29, 65, 21, 78, 96, 30};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("<br>");
twoWaySelectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("<br>");
return 0;
}
Original array: 25 45 14 10 23 29 65 21 78 96 30 Sorted array: 10 14 21 23 25 29 30 45 65 78 96
Key Points
- Two-way selection sort reduces the number of passes to approximately n/2 compared to regular selection sort.
- The algorithm handles the special case where the maximum element is swapped to the minimum position during the first swap.
- Time complexity remains O(n²) but with fewer iterations in practice.
Conclusion
Two-way selection sort offers a practical improvement over traditional selection sort by processing elements from both ends simultaneously, reducing the number of passes required while maintaining the same overall time complexity.
Advertisements
