The array is sorted from small to big. Insert a number x so it stays sorted. How: go from the last one back, shift each one bigger than x back one cell, stop at the first one not bigger, and put x in the gap. Finish insert(a, n, x), which returns the new count. The program inserts 6 (middle), 0 (front), 10 (end).
1 3 5 6 7 9 0 1 3 5 6 7 9 0 1 3 5 6 7 9 10
#include <stdio.h>
int insert(int a[], int n, int x) {
int i = n - 1;
while (i >= 0 && a[i] > x) {
// your code here: shift a[i] back one cell
i--;
}
// your code here: put x in the empty cell
return n + 1;
}
void show(int a[], int n) {
for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
printf("\n");
}
int main(void) {
int a[10] = {1, 3, 5, 7, 9};
int n = 5;
n = insert(a, n, 6);
show(a, n);
n = insert(a, n, 0);
show(a, n);
n = insert(a, n, 10);
show(a, n);
return 0;
}
Run tries the examples. When they look right, Submit.