C Programming - HOW TO FIX THIS? void selection_sort(int a[], int n){ int *large
ID: 671759 • Letter: C
Question
C Programming - HOW TO FIX THIS?
void selection_sort(int a[], int n){
int *largest = 0;
if(n == 1){
return;
}
largest = find_largest(a, n);
if(*largest < n - 1){
swap(&a[n-1], &a[n]);
}
selection_sort(a, n - 1);
}
int *find_largest(int *a, int n){
int *p, *max = 0;
*max = *a;
for (p = a; p < a + n; p++){
if (*p > *max){
*max = *p;
}
}
return max;
}
void swap(int *p, int *q){ //exchange value of two variables
int temp = *p;
*p = *q;
*q = temp;
}
Explanation / Answer
/*
Points: Functions hould always be declared in C before it is used in the program.
Also, we have to be very sure while using pointesr to receive the function args as an incorrect way of using the pointer comparison/arithmetic may well lead to a dangling address which can be really difficult to debug.
Hope this solution clears all the doubts. Comments aree provided as well.
Thanks.
*/
#include <stdio.h>
#define MAXSIZE 100
//functions should be declared before it is used in a C prog
int find_largest(int b[10], int k);
void selection_sort(int b[10], int k);
void swap(int*, int*);
//Code Flow Controller
void main()
{
int array[MAXSIZE]; // initializing an array of size 100, you can change the arrays size as per your wish or take input from user for array size as well, and allocate dynamically.
int i, j, n, temp;
/* taking array elements as input */
printf("Enter the size of array ");
scanf("%d", &n);
printf("Enter the elements one by one ");
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
/* Printing the array elements before its Sorted */
printf("Input array elements ");
for (i = 0; i < n ; i++)
{
printf("%d ", array[i]);
}
/* Selection sorting begins here*/
selection_sort(array, n);
/* Printing the array elements after Sorting */
printf("Sorted array is... ");
for (i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
}
//function to exchange value of two variables after checking for the largest elemet
void selection_sort(int b[10], int n)
{
int temp, largest, j;
for (j = n - 1; j >= 1; j--)
{
largest = find_largest(b, j);
swap(&b[largest],&b[j]);
}
return;
}
// function to find the maximum value
int find_largest(int *b, int n)
{
int max = 0, j;
for (j = 1; j <= n; j++)
{
if (*(b+j) > *(b+max))
{
max = j;
}
}
return(max);
}
//exchange value of two variables
void swap(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.