import java.util.Arrays;
public abstract class Sort {
protected Comparable[] toBeSortedArray;
public Sort(Comparable[] toBeSortedArray) {
this.toBeSortedArray = toBeSortedArray;
}
protected boolean less(int i, int j) {
return toBeSortedArray[i].compareTo(toBeSortedArray[j]) < 0;
}
protected void exch(int i, int j) {
Comparable temp = toBeSortedArray[i];
toBeSortedArray[i] = toBeSortedArray[j];
toBeSortedArray[j] = temp;
}
protected boolean isSorted() {
for (int i = 1; i < toBeSortedArray.length; i++)
if (!less(i-1,i))
return false;
return true;
}
public abstract void sort();
}
class SelectionSort extends Sort {
public SelectionSort(Comparable[] toBeSortedArray) {
super(toBeSortedArray);
}
@Override
public void sort() {
for (int i = 0; i < toBeSortedArray.length; i++) {
int min = i;
for (int j = i+1; j < toBeSortedArray.length; j++) {
if (less(j,min))
min = j;
}
exch(i,min);
}
}
public static void main(String[] args) {
Integer[] testArray = {5,8,4,1,2,3,7,9,6,0};
SelectionSort selectionSort = new SelectionSort(testArray);
selectionSort.sort();
System.out.println(selectionSort.isSorted());
System.out.println(Arrays.toString(testArray));
}
}
class InsertionSort extends Sort {
public InsertionSort(Comparable[] toBeSortedArray) {
super(toBeSortedArray);
}
@Override
public void sort() {
int N = toBeSortedArray.length;
for (int i = 1; i < N; i++) {
for (int j = i; j >= 1 && less(j,j-1); j--)
exch(j,j-1);
}
}
public static void main(String[] args) {
Integer[] testArray = {5,8,4,1,2,3,7,9,6,0};
InsertionSort insertionSort = new InsertionSort(testArray);
insertionSort.sort();
System.out.println(insertionSort.isSorted());
System.out.println(Arrays.toString(testArray));
}
}
class BubbleSort extends Sort {
public BubbleSort(Comparable[] toBeSortedArray) {
super(toBeSortedArray);
}
@Override
public void sort() {
int N = toBeSortedArray.length;
for(int i = 0 ; i < N-1; i++){
for(int j = 0 ; j < N-i-1; j++){
if(less(j+1,j)){
exch(j,j+1);
}
}
}
}
public static void main(String[] args) {
Integer[] testArray = {5,8,4,1,2,3,7,9,6,0};
BubbleSort bubbleSort = new BubbleSort(testArray);
bubbleSort.sort();
System.out.println(bubbleSort.isSorted());
System.out.println(Arrays.toString(testArray));
}
}
class ShellSort extends Sort {
public ShellSort(Comparable[] toBeSortedArray) {
super(toBeSortedArray);
}
@Override
public void sort() {
int N = toBeSortedArray.length;
int h = 1;
while (h < N/3)
h = 3*h + 1;
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(j,j-h); j-=h)
exch(j,j-h);
}
h = h/3;
}
}
public static void main(String[] args) {
Integer[] testArray = {5,8,4,1,2,3,7,9,6,0};
ShellSort shellSort = new ShellSort(testArray);
shellSort.sort();
System.out.println(shellSort.isSorted());
System.out.println(Arrays.toString(testArray));
}
}