Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads its input into an array and then uses selection sort

ID: 3810103 • Letter: W

Question

Write a program that reads its input into an array and then uses selection sort to sort the array. In selection sort, we first find the smallest element in the array and exchange it with the first array element's value; then we find the next smallest element in the array and exchange it with the second array element's value; and so on, until the array is sorted.

Have your program include 4 functions, besides main, which perform the following functions:

1. Read in an undetermined number of array elements.

2. Print the array elements (call this function both before and after the elements are sorted).

3. Sort the array elements.

4. Swap two elements of an array (this function will be called by your sort function).

Do not use any jump statement, e.g., the break statement.

Declare the maximum array size as a constant MAXSIZE with a value of 10.

Run your program with the following set of input:

1. 5 12 -7 3 0

2. 1 2 3 4 5 7 6

3. Some input that will trigger each of your errors checks, what happens when you enter more values than MAXSIZE or when invalid (nonnumeric) data is entered. Flush the invalid data and continue reading until EOF or the array is full. Print appropriate error message for invalid character data and for too many values. Data items should still be sorted, even if invalid character data is encountered or too many values are entered.

Explanation / Answer

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
int array[MAXSIZE];
int n=0;
void enterelements()
{
    int i=0,k;
    char ch='Y';
    while(ch=='Y' || ch=='y')
     {
    printf(" Enter the element");
    scanf("%d",&k);
    n++;
    if( n > MAXSIZE)
     {
       printf(" Number of elements is greater than MAXSIZE ");
       exit(0);
   }
  
      array[i]=k;
      i++;
      printf(" Do you want to continue");
      ch=getchar();
   }   


}
void print()
{
   int i;
   for(i=0;i<n;i++)
   printf("%d ", array[i]);  
}

void swap(int *x,int *y)
{
   int t;
   t=*x;
   *x=*y;
   *y=t;
}

void selectionsort()
{
   int i,j;
   for(i=0;i<n-1;i++)
   {
       for(j=i+1;j<n;j++)
       {
           if(array[i]>array[j])
           swap(&array[i],&array[j]);
       }
   }
}
int main()
{
   enterelements();
   print();
   selectionsort();
   printf("Sorted list using selection sort: ");
   print();
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote