Sitemap

Member-only story

Java Coding Problems

11 min readFeb 13, 2025

--

Sorting

Q1- Write a Java program to sort an integer array in non-decreasing order without using any built-in sorting functions from the Collections framework or the Arrays.sort() method. Implement a sorting algorithm of your choice (e.g., Bubble Sort, Selection Sort, or Insertion Sort)

a) Bubble Sort

Time Complexity: Worst-case: O(n²) , Average-case: O(n²)

Best-case: O(n) (when the array is already sorted)

Space Complexity: O(1) (in-place sorting)

public class BubbleSort {
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j + 1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}

public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(array);
System.out.println("Sorted array using Bubble Sort:");
for (int num : array) {
System.out.print(num + " ");
}
}
}

--

--