0% found this document useful (0 votes)
6 views2 pages

Selection Sort

The document contains a C program that implements the Selection Sort algorithm to sort an array of random integers. It generates arrays of varying sizes, measures the time taken to sort each array, and prints the results. The program also includes functions for generating random numbers and measuring time using high-resolution timers.

Uploaded by

rakeshyella1410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Selection Sort

The document contains a C program that implements the Selection Sort algorithm to sort an array of random integers. It generates arrays of varying sizes, measures the time taken to sort each array, and prints the results. The program also includes functions for generating random numbers and measuring time using high-resolution timers.

Uploaded by

rakeshyella1410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Selection sort

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Function to perform Selection Sort

void selectionSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

// Find the minimum element in unsorted array

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

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

// Function to generate an array of random integers

void generateRandomArray(int arr[], int n) {

for (int i = 0; i < n; i++) {

arr[i] = rand() % 10000; // Random numbers between 0 and 9999

}
// Function to get high-resolution time

double get_time_in_seconds() {

struct timespec start;

clock_gettime(CLOCK_MONOTONIC, &start);

return start.tv_sec + start.tv_nsec / 1e9;

int main() {

srand(time(NULL)); // Seed the random number generator

// Test the program with different sizes of n

for (int n = 5000; n <= 50000; n += 5000) {

int *arr = (int*) malloc(n * sizeof(int)); // Allocate memory for the array

// Generate a random array

generateRandomArray(arr, n);

// Measure the time taken for Selection Sort

double start_time = get_time_in_seconds();

selectionSort(arr, n);

double end_time = get_time_in_seconds();

double time_taken = end_time - start_time;

printf("Time taken to sort %d elements using Selection Sort: %f seconds\n", n, time_taken);

free(arr); // Free the allocated memory

return 0;

You might also like