# Thread: Sorting an array into increasing values by passing pointers as function arguments

1. ## Sorting an array into increasing values by passing pointers as function arguments

I'd like to be able to add code to my program which sorts the elements of an array into increasing value. Can this be done in the following way (is it called bubble sorting?)?

for (i=0;i<4;i++)
for (p=(i+1);p<4;p++)
if pointer1[i]>pointer1[p]
temp=pointer1[i];
pointer1[i]=pointer1[p];
pointer1[p]=temp;

What I mean to ask is, can pointers be used in arrays? Or does that defeat the objective of using pointers?

Thanks 2. Can't think of what this would be called but I don't think it is a bubble sort that you've got there (maybe it is, I can't remember the particular behavior of all the sorts I had to study in school: bubble, selection, insertion, radix, merge, quick sort, etc...). Yes you can do this. Say you have an array of 4 integers to sort. With some modifications, your code could be put into a function like so:

Code:
```void MySort( int* pointer)
{
int i, p, temp;

for( i = 0; i < 3; i++ ) // Needs to be one less than size of array
for( p = i+1; p < 4; p++ )
if( pointer[i] > pointer[p] ) // Or "if( *(pointer+i) > *(pointer+p) )
{
temp = pointer[i];          // Or "temp = *(pointer+i);"
pointer[i] = pointer[p];   // Or "*(pointer+i) = *(pointer+p);"
pointer[p] = temp;         // Or "*(pointer+p) = temp;"
}

}```
You can call it like so:

Code:
```int Array = { 18, 12, 14, 16 };
MySort( Array ); // Array will now be 12, 14, 16, 18 after call``` 3. ## Reply

Just tried it and it works a treat!

Thanks very much! Popular pages Recent additions 