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

Your C program will output the series of reversals of given unique integers up t

ID: 3546057 • Letter: Y

Question

Your C program will output the series of reversals of given unique integers up to 200>=0, terminated by -5. The integers will be sorted in ascending order using a series of reversals(swap/selection/permutation). Your program should only use a single array.


I will do the series of reversals by hand, but I was not able to get the right code for the output.


Input:

7 1 8 2 4 -5

by hand: reversal or swap from above input

8 1 7 2 4  <---   3

4 2 7 1 8   <---  5

7 2 4 1 8   <---  3

1 4 2 7 8    <--   4

4 1 2 7 8   <---  2

2 1 4 7 8   <---  3

2 1 4 7 8   <---  1

1 2 4 7 8   <---- 2

Note: Ignore the hand solution, it was used to show how the series of reversals for the input worked.

Therefore, output is: 3 5 3 4 2 3 1 2

Explanation / Answer

#include <stdio.h>


void reverse(int data[], int size)

{

int i = 0, j = size - 1;

int tmp;

while (i < j)

{

tmp = data[i];

data[i] = data[j];

data[j] = tmp;

i++;

j--;

}

}


int main()

{

int data[200]; /* max to 200 */

int num = 0;

int i, j, m;

printf("Enter numbers (-5 to end): ");

scanf("%d", &data[num]);

while (data[num] >= 0)

{

num++;

scanf("%d", &data[num]);

}

  

/* start to sort */

for (i = num - 1; i > 0; i--)

{

m = 0;

for (j = 1; j <= i; j++)

{

if (data[j] > data[m])

m = j;

}

reverse(data, m + 1);

printf("%d ", m + 1);

reverse(data, i + 1);

printf("%d ", i + 1);

}

printf(" ");

/* print sorted array */

printf("Sorted: ");

for (i = 0; i < num; i++)

printf("%d ", data[i]);

printf(" ");

  

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