Sorting Algorithms
Sorting Algorithms
Output:
Aim: Write a Program to sort an array using Insertion Sort.
Code:
public class InsertionSort {
public static void main(String[] args) {
int arr[] = {10, 1, 3, 12, 33, 90, 89};
int n = arr.length;
Insort is = new Insort();
is.InsSort(arr, n);
System.out.print("Sorted Arrays: ");
displays ds = new displays();
ds.display(arr, n);
}
Output:
Aim: Write a Program to sort an array using Selection Sort.
Code:
public class SelectionSort {
public static void main(String[] args) {
SelectionSort sb = new SelectionSort();
int arr[] = {75, 85, 19, 78, 90, 8};
int n = arr.length;
sb.SelSort(arr, n);
System.out.println("Sorted Arrays: ");
sb.printArray(arr, n);
}
//print arrays
void printArray(int arr[], int n) {
n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Aim: Write a Program to sort an array using Quick Sort.
Code:
public class QuickSortLast {
public static void main(String[] args) {
int[] arr = {70, 67, 11, 2, 3, 46};
int n = arr.length;
QuickSortLast qs = new QuickSortLast();
qs.sort(arr, 0, n - 1);
System.out.println("Sorted Arrays using Quick Sort: ");
qs.printArray(arr);
}
}
void merge(int arr[], int l, int m, int r) {
//finding size of two sub-arrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
//copy remaining elements of L[] if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
//copy remaining element of R[] if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
//merging method
merge(arr, l, m, r);
}
}
Output: