From 3d7da3a458fc1a16973235084fafbbb9c145456d Mon Sep 17 00:00:00 2001 From: ASWIN-KUMAR-5 Date: Sat, 19 Oct 2024 01:07:18 +0530 Subject: [PATCH] Create Selection Sort.cpp --- Selection Sort.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Selection Sort.cpp diff --git a/Selection Sort.cpp b/Selection Sort.cpp new file mode 100644 index 0000000..a241ead --- /dev/null +++ b/Selection Sort.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +void selectionSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + // Find the minimum element in the unsorted portion + int minIndex = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIndex]) { + minIndex = j; + } + } + // Swap the found minimum element with the first element + if (minIndex != i) { + swap(arr[i], arr[minIndex]); + } + } +} + +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + cout << endl; +} + +int main() { + int arr[] = {64, 25, 12, 22, 11}; + int n = sizeof(arr) / sizeof(arr[0]); + + cout << "Original array: "; + printArray(arr, n); + + selectionSort(arr, n); + + cout << "Sorted array: "; + printArray(arr, n); + + return 0; +}