Skip to content

Instantly share code, notes, and snippets.

@youngdze
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youngdze/a117b2b55fb662d414bf to your computer and use it in GitHub Desktop.
Save youngdze/a117b2b55fb662d414bf to your computer and use it in GitHub Desktop.
Sort algorithm in Java
public class Sort {
public static void main(String[] args) {
int arr[] = {2, 3, 1, 56, 88, 23, 10, 54, 40, 78, 29};
// bubbleSort(arr);
// selectionSort(arr);
insertionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
private static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
}
}
}
}
private static void selectionSort(int[] arr) {
int i, j;
int min;
for (i = 0; i < arr.length - 1; i++) {
min = i;
for (j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
min = j;
}
}
if (min != i) {
swap(arr, min, i);
}
}
}
private static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length + 1; i++) {
for (int j = i - 1; j > 0 && arr[j] < arr[j - 1]; j--) {
swap(arr, j, j - 1);
}
}
}
private static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment