Sorting Algorithms
2 min readNov 9, 2022
All Sorting Algos
1. Bubble Sort
class HelloWorld { public static void main(String[] args) {
int arr[]= new int[]{-90, 6, 98, 34, 2, 11};
Bubble(arr);
for(int i: arr){
System.out.print(i + " ");
}
}
public static void Bubble(int arr[]){
for(int i = 0; i < arr.length - 1; i++){
boolean flag = false;
for(int j = 0; j < arr.length - i - 1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = true;
}
}
if(flag == false) break;
}
}
}
2. Selection Sort
class SelectionSort { public static void selectionSort(int array[]) { int size = array.length; for (int step = 0; step < size - 1; step++) {
int min_idx = step; for (int i = step + 1; i < size; i++) { if (array[i] < array[min_idx])
{
min_idx = i;
}
}
int temp = array[step];
array[step] = array[min_idx];
array[min_idx] = temp;
}
}// driver code public static void main(String args[]) { int[] data = { 20, 12, 10, 15, 2 };
SelectionSort ss = new SelectionSort();
ss.selectionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data)); }
}
3. Insertion Sort
class InsertionSort { public static void insertionSort(int array[]) {
int size = array.length; for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1; while (j >= 0 && key < array[j])
{
array[j + 1] = array[j];
--j;
}// Place key at after the element just smaller than it. array[j + 1] = key; }
}// Driver code public static void main(String args[]) { int[] data = { 9, 5, 1, 4, 3 };
InsertionSort is = new InsertionSort();
is.insertionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data)); }
}