I have a program that:
- given a sequence of numbers,
- sorts even numbers in ascending order, and
- sort odd numbers in descending order, and
- adds the sorted even numbers to an array followed by the sorted odd numbers.
Example:
Input: 1, 2, 3, 4, 5, 6
Expected output: 2, 4, 6, 5, 3, 1
Actual output: 1578032, 0, 3, 6, 6487408, 0
here is my code:
#include < stdio.h >
int main() {
input();
}
int input() {
int n;
printf("Enter The Number Of Elements You Want To Enter : ");
scanf("%d", & n);
int * ptr, i, ev = 0, od = 0;
ptr = (int * ) calloc(n, sizeof(int));
for (i = 0; i < n; i++) {
printf("Enter Number : ");
scanf("%d", (ptr + i));
if ( * (ptr + i) % 2 == 0) {
ev++;
} else {
od++;
}
}
sorteven( & ptr, ev, od, n);
}
int sorteven(int * ptr, int ev, int od, int n) {
int i, j = 0, swap = 0, * ptreven;
ptreven = (int * ) calloc(ev, sizeof(int));
for (i = 0; i < n; i++) {
if ( * (ptr + i) % 2 == 0) { *
(ptreven + j) = * (ptr + i);
j++;
}
}
for (i = 0; i < ev - 1; i++) {
for (j = 0; j < ev - i - 1; j++) {
if ( * (ptreven + j) > * (ptreven + j + 1)) {
swap = * (ptreven + j); *
(ptreven + j) = * (ptreven + j + 1); *
(ptreven + j + 1) = swap;
}
}
}
sortodd( & ptr, ev, od, n, & ptreven);
}
int sortodd(int * ptr, int ev, int od, int n, int ptreven) {
int i, k = 0, swap = 0, * ptrodd, j;
ptrodd = (int * ) calloc(od, sizeof(int));
for (i = 0; i < n; i++) {
if ( * (ptr + i) % 2 != 0) { *
(ptrodd + k) = * (ptr + i);
k++;
}
}
for (i = 0; i < od - 1; i++) {
for (j = 0; j < od - i - 1; j++) {
if ( * (ptrodd + j) < * (ptrodd + j + 1)) {
swap = * (ptrodd + j); *
(ptrodd + j) = * (ptrodd + j + 1); *
(ptrodd + j + 1) = swap;
}
}
}
merge( & ptr, ev, od, n, & ptreven, & ptrodd);
}
int merge(int * ptr, int ev, int od, int n, int * ptreven, int * ptrodd) {
int * ptrmerge, i, j;
ptrmerge = (int * ) calloc(n, sizeof(int));
for (i = 0; i < ev; i++) { *
(ptrmerge + i) = * (ptreven + i);
}
for (i = ev, j = 0; i < n; i++, j++) { *
(ptrmerge + i) = * (ptrodd + j);
}
display( & ptrmerge, n);
}
int display(int * ptrmerge, int n) {
int i;
printf("OUTPUT : ");
for (i = 0; i < n; i++) {
printf(" %d ", * (ptrmerge + i));
}
}
like this