Skip to content

Commit

Permalink
Create SelectionSort.java
Browse files Browse the repository at this point in the history
Selection Sort is a simple, comparison-based sorting algorithm. It works by dividing the input list into two parts: a sorted and an unsorted section. The algorithm repeatedly selects the smallest (or largest, depending on the order) element from the unsorted section and swaps it with the first unsorted element, effectively growing the sorted section one element at a time.
  • Loading branch information
Veekshitha11 authored and x0lg0n committed Oct 29, 2024
1 parent b2b2167 commit 36033d7
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Java/SelectionSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
public class SelectionSort {

public static void selectionSort(int[] array) {
int n = array.length;

// Traverse through all array elements
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}

public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(array);

selectionSort(array);

System.out.println("Sorted array:");
printArray(array);
}

static void printArray(int[] array) {
for (int value : array) {
System.out.print(value + " ");
}
System.out.println();
}
}

0 comments on commit 36033d7

Please sign in to comment.