Click here to Skip to main content
15,906,816 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have an array of size 100, and some of its values are numbers and others are null.
Let's say [NULL][NULL][5][4][NULL][6]...
I try to sort the array with it's valid numbers.
Can I have a link to a sample explanation code?

Edit:
Array should be [NULL][NULL][4][5][NULL][6]...
Posted
Updated 30-Oct-11 10:34am
v2

Try the following steps:
  1. Record (valid) values and their positions in two new arrays.
  2. Sort array of values (you may now use any of the 'ordinary' sorting method like, for instance, std::sort).
  3. Use both the array of positions and the one of ordered values to replace numbers into the original array.


namely:
C++
#include <vector>
#include <algorithm>
using namespace std;

void mySort(int a[], size_t size)
{
  vector < int > pos;
  vector < int > val;
  for (size_t i=0; i<size; i++)
  {
    if ( a[i] != NULL)
    {
      pos.push_back(i);
      val.push_back(a[i]);
    }
  }

  sort(val.begin(),val.end());

  for (size_t i=0; i<pos.size(); i++)
    a[pos[i]] = val[i];
}
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 30-Oct-11 17:58pm    
Nice one! 5+
CPallini 30-Oct-11 18:34pm    
Thank you.
Maximilien 30-Oct-11 17:59pm    
nice.
CPallini 30-Oct-11 18:34pm    
Thank you.
Malli_S 31-Oct-11 4:31am    
Nice One !
so you just want to sort the "sub" arrays between the null entries ?

you could (I haven't tested it) loop the array to find the first and last index of each sequence and pass that to stl's sort, I think it works with arrays (you pass the index/addresses of the arrays.

good luck.

M.
 
Share this answer
 
Comments
CPallini 30-Oct-11 17:39pm    
[Moved from OP fake answer] Not quite there can be NULLS between numbers like
[null][5][null][null][2][null][3] -> [null][2][null][null][3][null][5]
We can also process an <int*> array
whose NULL-elements are "not inserted" but other elements can be 0 as well :)
C++
#include <stdlib.h>

int yourCompareFunc(const void *arg1, const void *arg2)
{
  if (arg1 && arg2) {
    return (*(int*)arg1) - (*(int*)arg2);
  }
  return 0;
}


void yourSort(int* piElements, int iElementsCount)
{
  qsort(piElements, iElementsCount, sizeof(int*), yourCompareFunc);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900