Sorting Algorithms: Principles, Complexity, and Java Implementations
Bubble Sort
Core Concept
With a dataset of size n, adjacent elements are compared either from left to right or right to left. If their order is incorrect (A[i-1] > A[i]), they are swapped. This process places the smallest element at the beginning of the unsorted portion, referred to as one pass of bubble sorting. In subsequent passes, the sorted elements are excluded from comparison, reducing the number of elements to be considered each time.
Implementation
package bubble.sort;
public class BubbleSort {
public static void sort(int[] array) {
int len = array.length;
boolean swapped;
for (int i = 0; i < len - 1; i++) {
swapped = false;
for (int j = 0; j < len - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void main(String[] args) {
int[] data = {5, 2, 4, 6, 8, 9, 7, 1, 3, 0};
sort(data);
}
}
Selection Sort
Core Concept
The algorithm starts by assuming the first element is the minimum. It then compares it with all remaining elements, updating the index of the minimum when a smaller value is found. After one complete scan, the minimum element is placed at the start of the unsorted section.
Implementation
package selection.sort;
public class SelectionSort {
public static void sort(int[] array) {
int len = array.length;
for (int i = 0; i < len - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < len; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
public static void main(String[] args) {
int[] data = {5, 2, 4, 6, 8, 9, 7, 1, 3, 0};
sort(data);
}
}
Insertion Sort
Core Concept
This method builds the final sorted array one item at a time. It takes each element from the input and inserts it into its correct position among the already sorted elements. The process continues until all items have been inserted.
Implementation
package insertion.sort;
public class InsertionSort {
public static void sort(int[] array) {
int len = array.length;
for (int i = 1; i < len; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
public static void main(String[] args) {
int[] data = {5, 2, 4, 6, 8, 9, 7, 1, 3, 0};
sort(data);
}
}