Skip to content

Instantly share code, notes, and snippets.

@arnu515
Created June 21, 2021 09:37
Show Gist options
  • Save arnu515/d05238a41c89094faaf49154cc65bfc8 to your computer and use it in GitHub Desktop.
Save arnu515/d05238a41c89094faaf49154cc65bfc8 to your computer and use it in GitHub Desktop.
Bubble, selection and insertion sort implemented in java
import java.util.Scanner;
import java.util.Random;
public class SortArray {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("1. Bubble sort\n2. Selection sort\n3. Insertion sort\n");
System.out.println("Enter integer:");
int choice = s.nextInt();
System.out.println("Enter array size (integer):");
int size = s.nextInt();
int[] arr = Sort.generateArray(size);
switch(choice) {
case 1:
System.out.println("Original array: ");
Sort.printArray(arr);
Sort.bubbleSort(arr);
System.out.println("After bubble sort: ");
Sort.printArray(arr);
break;
case 2:
System.out.println("Original array: ");
Sort.printArray(arr);
Sort.selectionSort(arr);
System.out.println("After selection sort: ");
Sort.printArray(arr);
break;
case 3:
System.out.println("Original array: ");
Sort.printArray(arr);
Sort.insertionSort(arr);
System.out.println("After insertion sort: ");
Sort.printArray(arr);
break;
}
}
}
class Sort {
/** Utility function */
public static int[] generateArray(int size) {
Random rand = new Random();
int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100);
}
return arr;
}
/** Utility function */
public static void printArray(int[] arr) {
System.out.print("[");
for (int i =0; i < arr.length; i++) {
System.out.print(arr[i] + (i == (arr.length - 1) ? "" : ", "));
}
System.out.println("]");
}
public static void bubbleSort(int[] input) {
int arrLength = input.length;
for (int i = 0; i < arrLength - 1; i++) {
for (int j = 0; j < arrLength - i - 1; j++) {
if (input[j] > input[j+1]) {
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
}
}
public static void selectionSort(int[] input) {
int arrLength = input.length;
for (int i = 0; i < arrLength; i++) {
int smallest = input[i];
int smallestPos = i;
for (int j = i; j < arrLength; j++) {
if (input[j] < smallest) {
smallest = input[j];
smallestPos = j;
}
}
int temp = input[i];
input[i] = input[smallestPos];
input[smallestPos] = temp;
}
}
public static void insertionSort(int[] input) {
int arrLength = input.length;
for (int i = 1; i < arrLength; i++) {
int compare = i;
for (int j = i-1; j >= 0; j--) {
if (input[compare] < input[j]) {
int temp = input[compare];
input[compare] = input[j];
input[j] = temp;
}
compare--;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment