0% found this document useful (0 votes)
2 views

Selection Sort

Uploaded by

Yashi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Selection Sort

Uploaded by

Yashi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <stdio.

h>

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


int i, j, min_index, temp;

// Loop to iterate over the array


for (i = 0; i < n-1; i++) {
// Assume the first element is the minimum
min_index = i;
// Loop to find the minimum element in the unsorted portion
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
// Swap the found minimum element with the first element
temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}

int main() {
int n, i;

// Take the size of the array as input


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Take array elements as input


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Call the selectionSort function


selectionSort(arr, n);

// Print the sorted array


printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

You might also like