Learn to implement and apply basic sorting algorithms: Bubble Sort and Insertion Sort.
public static int[] bubbleSort(int[] arr) {
int len = arr.length;
boolean swapped;
do {
swapped = false;
for (int i = 0; i < len - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return arr;
}
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
System.out.println(Arrays.toString(bubbleSort(numbers))); // [11, 12, 22, 25, 34, 64, 90]
public static int[] insertionSort(int[] arr) {
int len = arr.length;
for (int i = 1; i < len; i++) {
int current = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}
int[] numbers = {12, 11, 13, 5, 6};
System.out.println(Arrays.toString(insertionSort(numbers))); // [5, 6, 11, 12, 13]
Algorithm | Best Case | Average Case | Worst Case | Space | Stable |
---|---|---|---|---|---|
Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Modify the bubble sort algorithm to skip comparisons for already sorted elements at the end of the array.
public static int[] optimizedBubbleSort(int[] arr) {
// Your code here
return arr;
}
Extend insertion sort to work with an array of objects, sorting by a specified property.
public static void insertionSortByProperty(Object[] array, String propertyName) {
// Your code here
}
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Person[] people = {
new Person("John", 30),
new Person("Alice", 25),
new Person("Bob", 35)
};
// Example: sort by age (implement logic in insertionSortByProperty)
insertionSortByProperty(people, "age");
// Output: [{ name: 'Alice', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
If you want more practice with sorting algorithms, check out these resources: