Common sort algorithms include selection sort, insertion sort , glaring bubble sort and quicksort
Here are codes of above algorithm implemented in JAVA
/**
*
* @author blacklaw
*/
public class SortAlgorithmExample {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
sortTest(new SelectionSort());
sortTest(new InsertionSort());
sortTest(new BubbleSort());
sortTest(new QuickSort());
}
static void sortTest(Alignment ali){
long start, end;
start = System.nanoTime();
int[] origin = new int[]{16, 2, 3, 13, 5, 11, 10, 8, 9, 7, 6, 12, 4, 14, 15, 1};
int[] sorted = ali.sort(origin);
for (int i : sorted){
System.out.print(i + ", ");
}
end = System.nanoTime();
System.out.println(ali.getClass() + " " + Long.toString(end - start));
}
interface Alignment{
int [] sort(int[] origin);
}
static class SelectionSort implements Alignment{
@Override
public int[] sort(int[] origin) {
// TODO Auto-generated method stub
int t;
for (int i = 0; i < origin.length; i++){
int m = i;
for (int j = i + 1; j < origin.length; j++){
if (origin[j] < origin[m]){
m = j;
}
}
if (i != m){
t = origin[i];
origin[i] = origin[m];
origin[m] = t;
}
}
return origin;
}
}
static class BubbleSort implements Alignment{
@Override
public int[] sort(int[] origin) {
// TODO Auto-generated method stub
int t;
for (int i = 0; i < origin.length; i++){
for (int j = 0; j < origin.length - 1; j++){
if (origin[j] > origin[j+1]){
t = origin[j];
origin[j] = origin[j+1];
origin[j+1] = t;
}
}
}
return origin;
}
}
static class InsertionSort implements Alignment{
@Override
public int[] sort(int[] origin) {
// TODO Auto-generated method stub
for (int i = 1; i < origin.length; i++){
int t = origin[i];
int j = i - 1;
while (t < origin[j]){
origin[j+1] = origin[j];
j--;
if (j == -1){
break;
}
}
origin[j+1] = t;
}
return origin;
}
}
static class QuickSort implements Alignment{
@Override
public int[] sort(int[] origin) {
// TODO Auto-generated method stub
origin = quickSort(origin, 0, origin.length - 1);
return origin;
}
public int[] quickSort(int[] arr, int left, int right){
int t;
if (left < right){
int s = arr[left];
int i = left;
int j = right + 1;
while (true){
while (i+1 < arr.length && arr[++i] < s);
while (j-1 > -1 && arr[--j] > s);
if (i >= j){
break;
} else {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[left] = arr[j];
arr[j] = s;
quickSort(arr, left, j-1);
quickSort(arr, j+1, right);
}
return arr;
}
}
}