Skip to content
Open
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
48 changes: 48 additions & 0 deletions algorithms/SelectionSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <stdio.h>

void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;

// Find the index of the minimum element in the unsorted portion of the array
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Only swap if the minimum element is different from the current element
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}

int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

selectionSort(arr, n);

printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}