0% found this document useful (0 votes)
2 views1 page

Selection Sort

The document contains a Java class that implements two sorting algorithms: selection sort and insertion sort. It includes methods for sorting an array using each algorithm and a method to print the array. The main method demonstrates the functionality by sorting a predefined array using both algorithms and printing the results.

Uploaded by

ece apce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Selection Sort

The document contains a Java class that implements two sorting algorithms: selection sort and insertion sort. It includes methods for sorting an array using each algorithm and a method to print the array. The main method demonstrates the functionality by sorting a predefined array using both algorithms and printing the results.

Uploaded by

ece apce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

public class SortUsingSelectionAndInsertion {

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;
}
}
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 printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] selectionSortArr = {64, 25, 12, 22, 11};
int[] insertionSortArr = {64, 25, 12, 22, 11};
System.out.println("Original array for Selection Sort:");
printArray(selectionSortArr);
selectionSort(selectionSortArr);
System.out.println("Sorted array using Selection Sort:");

printArray(selectionSortArr);
System.out.println("\nOriginal array for Insertion Sort:");
printArray(insertionSortArr);
insertionSort(insertionSortArr);
System.out.println("Sorted array using Insertion Sort:");
printArray(insertionSortArr);
}
}

You might also like