diff --git a/algorithms/SelectionSort.c b/algorithms/SelectionSort.c new file mode 100644 index 0000000..7fcc614 --- /dev/null +++ b/algorithms/SelectionSort.c @@ -0,0 +1,48 @@ +#include + +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; +}