Answer the question
In order to leave comments, you need to log in
How to rearrange the elements of an array so that the positive components are first, then the zero ones, and then the negative components?
Help solve a programming problem (preferably code in C language)
Rearrange the elements of the array so that positive, then zero, and then negative components are located first, without changing the initial relative position of separately positive and separately negative components.
For example:
source array: -1 0 5 -9 8 -3 5 0 -7 4
result: 5 8 5 4 0 0 -1 -9 -3 -7
Answer the question
In order to leave comments, you need to log in
I think that you need to do a double sort like this:
#include <stdio.h>
int main() {
int arr[10] = {-1, 0, 5, -9, 8, -3, 5, 0, -7, 4};
int tmp = 0;
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++j) {
if(arr[j] < 1) {
tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
}
if(arr[j] < 0) {
tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
}
}
}
for(int i = 0; i < 10; ++i) printf("%d%c", arr[i], ' ');
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question