0% found this document useful (0 votes)
7 views1 page

Selection Sort 9 Program

The document contains a C program that implements the selection sort algorithm to sort an array of randomly generated integers. It prompts the user for the number of elements, generates the array, sorts it, and measures the time taken for the sorting process. The program also includes memory allocation for the array and proper cleanup after execution.

Uploaded by

Mangala Gouri
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)
7 views1 page

Selection Sort 9 Program

The document contains a C program that implements the selection sort algorithm to sort an array of randomly generated integers. It prompts the user for the number of elements, generates the array, sorts it, and measures the time taken for the sorting process. The program also includes memory allocation for the array and proper cleanup after execution.

Uploaded by

Mangala Gouri
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

#include <stdio.

h>
#include <stdlib.h>
#include <time.h>

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


int i, j, min_idx, temp;

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


min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

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


for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100000;
printf("%d ",arr[i]);

}
}

int main() {
int n;
printf("Enter the number of elements (n > 5000 recommended): ");
scanf("%d", &n);

int *arr = (int *)malloc(n * sizeof(int));

generateRandomArray(arr, n);

clock_t start = clock();


selectionSort(arr, n);
clock_t end = clock();

double time_taken = (double)(end - start) / CLOCKS_PER_SEC;


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

free(arr);
return 0;
}

You might also like