Last active
August 29, 2015 14:21
-
-
Save youngdze/a117b2b55fb662d414bf to your computer and use it in GitHub Desktop.
Sort algorithm in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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