Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions JAVA/Insertionsort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.util.Scanner;

public class Insertionsort{

public static void insertionsort(int arr[],int n){
for(int i=0;i<n;i++){
int j=i;
while(j>0 && arr[j-1]>arr[j])// It checks the comparision of numbers until the ith position and it makes sorted for every iteration.
{
int temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
j--;
}
}
System.out.println("After using InsertionSort");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args){
int arr[]={13,46,24,52,20,9};
int n=arr.length;
System.out.println("Before using InsertionSort");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
insertionsort(arr,n);
}
}
Empty file added JAVA/SelectionSort.java
Empty file.
51 changes: 51 additions & 0 deletions SelectionSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import java.util.Scanner;

public class SelectionSort {

public static void selectionSort(int arr[], int n) {
for (int i = 0; i <= n - 2; i++) {
// Find the index of the minimum element
int minIndex = i;

for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the minimum element with the current element
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;

// Print the array after each swap
System.out.print("After " + i + " Comparison: ");
for (int k = 0; k < n; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
}
System.out.println("After using Selection Sort:");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of the array:");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter the elements in the array:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Before using Selection Sort");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
selectionSort(arr, n);
}
}