Selection Sort

PHOTO EMBED

Mon Oct 14 2024 00:28:29 GMT+0000 (Coordinated Universal Time)

Saved by @deshmukhvishal2 #cpp

#include <iostream>
using namespace std;

// Function to sort the array using insertion sort algorithm.
void processSelectionSort(int arr[], int n) {
  
  for (int i = 0 ;i<n;i++){
    int minIndex=i;
     for (int j = i ;j<n;j++){
        if(arr[j]<arr[minIndex]){
           minIndex = j;
        }
    }
    std::swap(arr[i],arr[minIndex]);
  }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processSelectionSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
content_copyCOPY