Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

1.Write a program to sort list of n elements using selection sort. || DAA

1.Write a program to sort list of n elements using selection sort.

#include <stdio.h>

void swap(int *xp, int *yp) {

int temp = *xp;

*xp = *yp;

*yp = temp;

}

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

int i, j, min_index;

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

// Assume the current index is the minimum

min_index = i;

// Find the index of the minimum element in the unsorted part

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

swap(&arr[min_index], &arr[i]);

}

}

int main() {

int n, i;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n); 

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

scanf("%d", &arr[i]); 

printf("\nOriginal Array: "); 

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

printf("%d ", arr[i]); 

selectionSort(arr, n); 

printf("\nSorted Array: "); 

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

printf("%d ", arr[i]); 

return 0; 


Post a Comment

0 Comments