Sorting arrays is a basic but important concept in programming. In interviews, you're often asked to sort an array without using built-in methods like Arrays.sort()
. In this post, we'll explore how to sort an array manually using Bubble Sort and Selection Sort in Java.
1️⃣ Bubble Sort in Java
Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order. It's simple but not the most efficient for large datasets.
public class BubbleSortExample {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.print("Sorted Array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
2️⃣ Selection Sort in Java
Selection Sort selects the smallest element from the unsorted array and places it at the beginning.
public class SelectionSortExample {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// swap arr[i] and arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
System.out.print("Sorted Array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
🧠Interview Tip
Always ask if you can use built-in methods. If not, explain the time complexities: Bubble Sort is O(n²), Selection Sort is O(n²). For better performance, learn Merge Sort or Quick Sort as well.
✅ Output
Sorted Array: 2 3 4 5 8 Sorted Array: 11 12 22 25 64
📌 Conclusion
We learned how to sort an array in Java without using built-in methods like Arrays.sort()
. These basic sorting algorithms are essential for interviews and improving algorithmic thinking.