public class sortTimes {
// selection sort
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// bubble sort
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (array[j] > array[j+1]) {
// swaps array[j] and array[j+1]
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
// merge sort
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void merge(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left; i <= right; i++) {
arr[i] = temp[i - left];
}
}
// insertion sort
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
// selection sort
int[] arr1 = {5, 4, 3, 2, 1};
long selectionStart = System.nanoTime(); // get time before selection sort
selectionSort(arr1);
long selectionEnd = System.nanoTime(); // get time after selection sort
double selectionTotalTime = selectionEnd - selectionStart; // time to sort
System.out.println("Time for Selection Sort:" + selectionTotalTime);
// bubble sort
int[] arr2 = {5, 4, 3, 2, 1};
long bubbleStart = System.nanoTime(); // get time before bubble sort
bubbleSort(arr2);
long bubbleEnd = System.nanoTime(); // get time after bubble sort
double bubbleTotalTime = bubbleEnd - bubbleStart; // time to sort
System.out.println("Time for Bubble Sort:" + bubbleTotalTime);
// merge sort
int[] arr3 = {5, 4, 3, 2, 1};
long mergeStart = System.nanoTime(); // get time before merge sort
mergeSort(arr3, 0, arr3.length - 1);
long mergeEnd = System.nanoTime(); // get tune after merge sort
double mergeTotalTime = mergeEnd - mergeStart; // time to sort
System.out.println("Time for Merge Sort:" + mergeTotalTime);
// insertion sort
int[] arr4 = {5, 4, 3, 2, 1};
long insertionStart = System.nanoTime(); // get time before merge sort
insertionSort(arr4);
long insertionEnd = System.nanoTime(); // get tune after merge sort
double insertionTotalTime = insertionEnd - insertionStart; // time to sort
System.out.println("Time for Insertion Sort:" + insertionTotalTime);
}
}
sortTimes.main(null);