Seletion Sort
Write a c program to sort array using selection sort #include<stdio.h> #include<conio.h> void main() { int arr[30],i,n; void select_sort (int[],int); printf("\nEnter no of elements"); scanf("%d",&n); printf("\nEnter %d value",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); printf("\nBefore sorting elements are"); for(i=0;i<n;i++) printf("%d ",arr[i]); select_sort (arr,n); printf("\nAfter sorting elements are"); for(i=0;i<n;i++) printf("%d ",arr[i]); } void select_sort(int arr[],int n) { int temp,i,j,pos; for(i=0;i<n;i++) { pos=i; for(j=i+1;j<n;j++) { if (arr[j]<arr[pos]) pos=j; } temp=arr[pos]; arr[pos]=arr[i]; arr[i]=temp; } }
#include <stdio.h> // Function to perform selection sort void select_sort(int arr[], int n) { int temp, i, j, pos;
// Loop through all elements
for (i = 0; i < n - 1; i++) {
pos = i; // Assume the current position holds the minimum value
// Find the smallest element in the unsorted part of the array
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[pos]) {
pos = j; // Update the position of the smallest element
}
}
// Swap the found smallest element with the first unsorted element
temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
}
}
int main() { int arr[30], i, n;
// Input the number of elements in the array
printf("\nEnter number of elements: ");
scanf("%d", &n);
// Input the elements of the array
printf("\nEnter %d values: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the array before sorting
printf("\nBefore sorting, elements are: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Call the selection sort function
select_sort(arr, n);
// Display the array after sorting
printf("\nAfter sorting, elements are: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
} Enter number of elements: 5 Enter 5 values: 64 25 12 22 11 Before sorting, elements are: 64 25 12 22 11 After sorting, elements are: 11 12 22 25 64