The following code creates a Sorting Array using Pointers and functions correctly. The issue I have is I want the array to sort, but put the zeros at the end. Any help would appreciated.

``````#include <iostream>
using namespace std;

#include <iomanip>
using std::setw;

void selectionSort( int * const, const int ); // prototype
void swap( int * const, int * const ); // prototype

int main()
{
const int arraySize = 8;
int a[ arraySize ] = { 3, 0, -5, 9, 22, 0, 14, 7 };

selectionSort( a, arraySize ); // sort the array

cout << "Integers in ascending order\n";

for ( int j = 0; j < arraySize; j++ )
cout << setw( 4 ) << a[ j ];

cout << endl;
return 0; // indicates successful termination
} // end main

// function to sort an array
void selectionSort( int * const array, const int size )
{
int smallest; // index of smallest element

for ( int i = 0; i < size - 1; i++ )
{
smallest = i; // first index of remaining array

// loop to find index of smallest element
for ( int index = i + 1; index < size; index++ )

if ( array[ index ] < array[ smallest ] )
smallest = index;

swap( &array[ i ], &array[ smallest ] );
}
}

// swap values at memory locations to which
// x and y point
void swap( int * const x, int * const y )
{
int temp = *x;
*x = *y;
*y = temp;
}
``````

## All 3 Replies

HI
As I understand your problem is to sort an array in ascending and place the zero at last, and you have done up to sorting one last step[ u have to is that pick the first element to a temp. variable and shift the array element to one step back i.e.,

``````temp=array[0];
for(i=0;i<no_array_element;i++
array[i]=array[i+1];

array[no_array_element]=temp;``````

this code is when your array is sorted then zero must be at your 0th location of array if you have only one zero if more than zero will be occur then you to check for zero and repaid this step............
Best Of Luck.

I don't understand

You need to clarify your original problem ...

1. Are you wanting, to instead, sort the array in descending order?

Or...

1. having sorted the array in ascending order,
do you THEN want to move the element at index 0,
to the memory location at index size-1,
having moved all the elements up one place first?

If 2. is the case, then @prvnkmr449 has supplied the steps.

This edit make help?

``````int tmp = array[0]; // get copy of element at index 0

for( int i = 0; i < arraySize-1; ++ i )
array[i] = array[i+1]; // copy-over  / move each element up one

array[arraySize-1] = tmp;
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.