# Thread: Sorting array problem :)

1. ## Sorting array problem :)

Hello everyone here. Im new and yes that is my homework im not going to lie.
I need to write a program that doen't exactly sort an array. I will give an example
If i have that array : 1,3,0,2,0,-1,0,-2,-4,0
After transformations... the same array must be -1,-2,-4,0,0,0,0,1,3,2
The numbers<0 in the left part
The numbers == 0 in the middle
The numbers > 0 after the nulls in the right part.
Okay here is the problem. I must use only one array.
I can do it to make the program to this point -1,-2,-4,0,0,0,0 but with the positive numbers i've got a big problem . Here is my code.
Code:
```#include <iostream.h>

int main() {
const int K=10;
int array[K]={1,3,0,2,0,-1,0,-2,-4,0},i,b=0,m;
for(i=0;i<K;i++)
cout << array[i] << " ";
cout << endl;
for(i=0;i<K;i++)
if(array[i]<0) {
m=array[b];
array[b]=array[i];
array[i]=m;
b++;
}
for(i=b;i<K;i++)
if(array[i]==0) {
m=array[b];
array[b]=array[i];
array[i]=m;
b++;
}
for(i=0;i<K;i++)
cout << array[i] << " ";
cout << endl;
return 0;
}```
and the output is
Code:
```1 3 0 2 0 -1 0 -2 -4 0
-1 -2 -4 0 0 0 0 3 1 2```
... 3 1 2 It must be 1 3 2.
Sorry for my english. Im not native.
I would be happy if you give me some ideas.

2. Not sure what would be best, but you can probably use bubble-sort with a different swapping condition (if first > 0 and second < 0 then swap).

3. 10x for the fast reply but i dont need to sort the array in ascending/descending order.
The numbers in my array must follow this rule : first negative number must be the first number in the array without caring if its smaller/larger than the next and so on.

4. This assignment is the first step toward implementing quicksort -- get all the elements less than the pivot to the left, and all of the elements greater than the pivot to the right, where the pivot is 0 in this case.

The relative order must also be preserved, which means this sort is stable. So what you want to study is a reference implementation of a stable quicksort pivot.

5. Oh my Mighty Lord. sufoode your code works for God's sake.
But what is that memmove thing ?

6. Thank you very much sufoode and to all who read that problem.

7. Okay i wish to thank to all of you once again.
I used as the other guys said some kind of bubble sort to do the assignment.
Here is my last code
(if someone has the same problem)
Code:
```#include <iostream.h>
void swap(int& a,int& b);
int main() {
const int K=10;
int array[K];
int i,j,b=0;
bool nulls=false;
for(i=0;i<K;i++) {
cin >> array[i];
if(!cin) { cout << "Error ! Enter integers!\n"; return 1; }
}
for(i=0;i<K;i++)
if(array[i]==0) nulls=true;
else if(array[i]<0) {
for(j=i;j>b;j--)
swap(array[j],array[j-1]);
b++;
}
if(nulls==true)
for(i=b;i<K;i++)
if(array[i]==0) {
for(j=i;j>b;j--)
swap(array[j],array[j-1]);
b++;
}
for(i=0;i<K;i++)
cout << array[i] << ' ';
cout << endl;
return 0;
}
void swap(int& a,int& b) {
a=a+b;
b=a-b;
a=a-b;
}```