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

This should be written in \" C \"!!!! Given a list of integers, write a C functi

ID: 3813450 • Letter: T

Question

This should be written in " C "!!!!

Given a list of integers, write a C function, similar to the partition process in QuickSort, that will rearrange the integers so that either all the integers in evennumbered positions will be even or all the integers in odd-numbered positions will be odd. (Your function will provide a proof that one or the other of these goals can always be attained, although it may not be possible to establish both at once.) Your main program will read a set of values from DataIn file, and print out the list after reordering them as the above.

*Note: sample data input in DataIn file for Q4

11

3 1 4 5 9 6 8 0 7 13 16

Explanation / Answer

#include <stdio.h>


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

void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void partition(int arr[], int n)
{
int i = 0;
int temp;
int j = 1;
while(1)
{
// Traverse even position to have proper data on even
while(i < n && j < n && arr[i] % 2 == 0)
{
i = i+2;
}
// Traverse odd data to have proper data o odd
while(i < n && j < n && arr[j] % 2 != 0)
{
j += 2;
}

// exchange data if ourt of order
if (i < n && j < n)
{
swap(&arr[i], &arr[j]);
i = i+2;
j = j+2;
}

// break if all of the data is read once
if (i >= n || j >= n)
break;
}
}

int main()
{
FILE *fp = fopen("DataIn", "r");
int n;

fscanf(fp, "%d", &n);

int arr[n]; // test data with n = 11, {3,1,4,5,90,6,8,0,7,13,16};

int i;
for(i = 0; i < n; i++)
{
fscanf(fp, "%d", &arr[i]);
}

partition(arr, n);

print(arr, n);
return 0;
}

Sample run

6 1 4 5 0 3 8 9 7 13 16

There can be three situations:

Please rate positively if this solved your problem. Please comment if something is not clear.

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