Data Structures Practical 8

Question 1
Modify the Selection Sort algorithm to handle arrays containing negative numbers.
selectionsort.c
C
				#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define max 50

void selection(int arr[], int size);
int Min(int a[], int start, int end);

void main()
{
    int arr[max];
    int i, size;
    clrscr();
    printf("Enter the number of elements in the array :");
    scanf("%d", &size);
    printf("Enter array elements :");
    for (i = 0; i < size; i++)
    {
        printf("\nEnter element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    selection(arr, size);
    printf("\nThe sorted elements are :\n");
    for (i = 0; i < size; i++)
        printf("%d\t", arr[i]);
    getch();
}

void selection(int a[], int size)
{
    int i = 0, loc = 0, temp = 0;
    for (i = 0; i < size; i++)
    {
        loc = Min(a, i, size);
        temp = a[loc];
        a[loc] = a[i];
        a[i] = temp;
    }
}

int Min(int a[], int start, int end)
{
    int i, small = a[start], pos = start;
    for (i = start + 1; i < end; i++)
    {
        if (a[i] < small)
        {
            small = a[i];
            pos = i;
        }
    }
    return (pos);
}

			
Output
Question 2
Adapt the Selection Sort algorithm to sort an array of floating-point numbers.
selectionfloat.c
C
				#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define max 50

void selection(float arr[], int size);
int Min(float a[], int start, int end);

void main()
{
    float arr[max];
    int i, size;
    clrscr();
    printf("Enter the number of elements in the array :");
    scanf("%d", &size);
    printf("Enter array elements :");
    for (i = 0; i < size; i++)
    {
        printf("\nEnter element %d: ", i + 1);
        scanf("%f", &arr[i]);
    }
    selection(arr, size);
    printf("\nThe sorted elements are :\n");
    for (i = 0; i < size; i++)
        printf("%f\t", arr[i]);
    getch();
}

void selection(float a[], int size)
{
    int i = 0, loc = 0;
	float temp;
    for (i = 0; i < size; i++)
    {
        loc = Min(a, i, size);
        temp = a[loc];
        a[loc] = a[i];
        a[i] = temp;
    }
}

int Min(float a[], int start, int end)
{
    int i, pos = start;
	float small = a[start]; 
    for (i = start + 1; i < end; i++)
    {
        if (a[i] < small)
        {
            small = a[i];
            pos = i;
        }
    }
    return (pos);
}

			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *