From 39add3f2b814319c9c0e8ba1fc420ebeebbe22e7 Mon Sep 17 00:00:00 2001 From: DIPAK KUMAL <67213707+Dipak1203@users.noreply.github.com> Date: Sun, 1 Oct 2023 22:22:38 +0545 Subject: [PATCH] Create SelectionSort.c Solving selection sort using C. --- algorithms/SelectionSort.c | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 algorithms/SelectionSort.c 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; +}