Sort:
1. Bubble
import java.util.Arrays; // Import Arrays class
//Bubble Sort
class BubbleSort {
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]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
}
public static void main(String args[]) {
int array[] = {1, 7, 5, 6};
bubbleSort(array); // Sort the array
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array)); // Print the sorted array
}
}
2. Selection
import java.util.Arrays; // Import Arrays class
//Selection Sort
class ArrayDemo {
public static void selectionSort(int array[]) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
int tmp = array[min_idx];
array[min_idx] = array[i];
array[i] = tmp;
}
}
public static void main(String args[]) {
int array[] = {1, 7, 5, 6, 2, -1};
selectionSort(array); // Sort the array
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array)); // Print the sorted array
}
}
3. Selection
import java.util.Array
//Insert Sort
class ArrayDemo {
public static void insertSort(int array[]) {
int n = array.length;
for(int i = 1; i<n;i++){
int key = array[i];
int j=i-1;
//compare KEY with each element on the left of it until an element smaller than it is found
//for descending order, change key<array[j] to key>array[j];
while(j>=0 && key < array[j]){
array[j+1] = array[j];
--j;
}
array[j+1]=key;
}
}
//Driver code
public static void main(String args[]) {
int array[] = {1, 7, 5, 6, 2, -7, 3};
insertSort(array); // Sort the array
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array)); // Print the sorted array
}
}
- Divide and Conquer Algorithm
4. Quick: (1)Single (2)Qual
5. Merge