C question. a) Using C Code complete the function shown below that swaps the val
ID: 3850454 • Letter: C
Question
C question.
a) Using C Code complete the function shown below that swaps the values in array elements with indices i and j of an array, arr where arr, i and j are parameters to the function. void swap(int arr[], int i, int j) {//... } b) Using C code complete the function shown below that sorts its arr parameter (the length of which is given by the n parameter). You should use the selection sort algorithm discussed in class but modified so that it sorts the array from the last legal element down, by repeatedly finding the maximum value and swapping it with the right-most element of the unsorted part of the array. You should implement the algorithm iteratively, using nested for loops. void ssort_down(int arr[], int n) {//... } c) Using C code complete the function shown below that returns the index of the maximum value in the sub-array of arr from indices start to end where arr, start and end are parameters to the function. The function must be written recursively and must not contain any loops. int max(int arr[], int start, int end) {//... } d) Using C code complete the function shown below that sorts its arr parameter (the length of which is given by the n parameter) using the "backwards" selection sort algorithm that behaves in the same way as the function you implemented iteratively in part (b). Your function should call the two functions that you wrote in parts (a) and (c). The function must be written recursively and must not contain any loops. void rec_ssort(int arr[], int n) {//... }Explanation / Answer
a)
void swap(int arr[],int i,int j)
{
int temp; //variable to swap values...
//swapping...
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return ;
}
b)
void ssort_down(int arr[],int n)
{
int i=n-1,j;
int max;//variable to keep track of max value..
//sorting
int temp;//temp variable to swap
for(;i>=0;i--)
{
j=i;
max=i;
for(;j>=0;j--)
{
if(arr[j]>arr[max])
{
max = j;
}
}
//swapping...
temp=arr[i];
arr[i]=arr[max];
arr[max]=temp;
}
}
c)
int max(int arr[],int start,int end)
{
static int max=start;
if(arr[start]>arr[max])
{
max=start;//updating max....
}
if(start==end)
{
return max;
}
return max(arr,start+1,end);
}
d)
void rec_sort(int arr[],int n)
{
int i=n-1,j;
int max;//variable to keep track of max value..
//sorting
int temp;//temp variable to swap
for(;i>=0;i--)
{
max = max(arr,0,i);//calling function in c) to find max index
swap(arr,max,i);//swapping max....in a)
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.