Data Structures Practical 9
Question 1
Write a C program to sort an array of Strings using Selection Sort.
selectionstr.c
C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ELEMENTS 50
#define MAX_LENGTH 30
void selection(char arr[MAX_ELEMENTS][MAX_LENGTH], int size);
int Min(char a[MAX_ELEMENTS][MAX_LENGTH], int start, int end);
void main()
{
char arr[MAX_ELEMENTS][MAX_LENGTH];
int i, size;
clrscr();
printf("Enter the number of elements in the array: ");
scanf("%d", &size);
printf("Enter array elements:\n");
for (i = 0; i < size; i++)
{
printf("Enter string %d: ", i + 1);
scanf("%s",arr[i]);
//gets(arr[i]);
}
selection(arr, size);
printf("\nThe sorted elements are :\n");
for (i = 0; i < size; i++)
printf("%s\n", arr[i]);
getch();
}
void selection(char a[MAX_ELEMENTS][MAX_LENGTH], int size)
{
int i = 0, loc = 0;
char temp[MAX_LENGTH];
for (i = 0; i < size - 1; i++)
{
loc = Min(a, i, size);
strcpy(temp, a[loc]);
strcpy(a[loc], a[i]);
strcpy(a[i], temp);
}
}
int Min(char a[MAX_ELEMENTS][MAX_LENGTH], int start, int end)
{
int i, pos = start;
char small[MAX_LENGTH];
strcpy(small, a[start]);
for (i = start + 1; i < end; i++)
{
if (strcmp(a[i], small) < 0)
{
strcpy(small, a[i]);
pos = i;
}
}
return (pos);
}
Output
Question 2
Extend your Selection Sort implementation to support case-insensitive sorting of strings. Ensure that uppercase and lowercase versions of the same letter are treated as equal during sorting.
selectionstr2.c
C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ELEMENTS 50
#define MAX_LENGTH 30
void selection(char arr[MAX_ELEMENTS][MAX_LENGTH], int size);
int Min(char a[MAX_ELEMENTS][MAX_LENGTH], int start, int end);
void main()
{
char arr[MAX_ELEMENTS][MAX_LENGTH];
int i, size;
clrscr();
printf("Enter the number of elements in the array: ");
scanf("%d", &size);
printf("Enter array elements:\n");
for (i = 0; i < size; i++)
{
printf("Enter string %d: ", i + 1);
scanf("%s",arr[i]);
//gets(arr[i]);
}
selection(arr, size);
printf("\nThe sorted elements are :\n");
for (i = 0; i < size; i++)
printf("%s\n", arr[i]);
getch();
}
void selection(char a[MAX_ELEMENTS][MAX_LENGTH], int size)
{
int i = 0, loc = 0;
char temp[MAX_LENGTH];
for (i = 0; i < size - 1; i++)
{
loc = Min(a, i, size);
strcpy(temp, a[loc]);
strcpy(a[loc], a[i]);
strcpy(a[i], temp);
}
}
int Min(char a[MAX_ELEMENTS][MAX_LENGTH], int start, int end)
{
int i, pos = start;
char small[MAX_LENGTH];
strcpy(small, a[start]);
for (i = start + 1; i < end; i++)
{
if (strcmpi(a[i], small) < 0)
{
strcpy(small, a[i]);
pos = i;
}
}
return (pos);
}
Output
