Tricky sorting algorithm

Hi ! This has been causing me a lot of hardship to find a reasonably elegant solution. I have an array of ints that I want to sort. Conditions are:
0-Do not touch element [0]
1-Remove all other empty entries between values in the array by shifting down the values and placing the '0' at the end
2-Keep track of a nonzero userValue position and rotate it with the array of ints
3-Rotate such that 'current position' is always the 3rd last nonzero element in the array of ints

**For example we have:**
1
2
3
int theValues[9] = {0, 40, 20, 0, 100, 60, 0, 66, 15};
int userValue = 4;
int position = 2; //the current position 

desired output is:
{0, 66, 15, 40, 20, 100, 60, 0, 0}
'userValue' is: 5



**Example 2:**
1
2
3
theValues[5] = {0, 11, 22, 33, 44};
userValue = 1;
position = 4;

desired output is:
{0, 33, 44, 11, 22}
'userValue' is: 3






This is my current (feeble) attempt. I was able to remove the zeros but the 2nd half with the rotation has me clueless. I think I'm close...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//declared and filled earlier
int theValues[MAX];  
int userValue;
int position;


//in function
//REMOVE ZEROS AND SHIFT ELEMENTS
int zeroCounter = 0;  //counts the number of zeros that need to shift
for(int i=1; i<=(MAX-zeroCounter); i++)	
{
   if (theValues[i] == 0)
   {			   
      for(int j=i; j<=(MAX-zeroCounter); j++)	
      {
         theValues[j] = theValues[j+1];
      }					 			 
      zeroCounter += 1;
      theValues[1+MAX-zeroCounter] = 0;

      if(userValue== (i+1) )
      {
         if(userValue== 1)	
            userValue= MAX - zeroCounter;
         else
            userValue -= 1;
      }
      if(position == (i+1) )
      {
         if(position == 1)	
            position = MAX - zeroCounter;
         else
            position -= 1;
      }
      i -= 1;
   } 
}

//ROTATE BASED ON 'position'
int valueCounter = MAX-zeroCounter;
int tempValue = theValues[valueCounter];

int offset = valueCounter- position;
int idealPosition = valueCounter - 3; //this is for the desired position of 3 from last nonzero element
int rotations = idealPosition - offset; //# of full rotations needed to sort
if(rotations < 0)
{
   rotations += valueCounter;
}

for(int i=0; i<rotations; i++)   
{
   for(int j=(valueCounter); j>=1; j--)
   {		
      if(j == 1)
      {
         theValues[j] = tempValue;
         tempValue = theValues[valueCounter];
      }
      else
      {
         theValues[j] = theValues[j-1];
      }
   }
   if(userValue == (i+1) )
   {
      if(userValue == 1)
         userValue = valueCounter;
      else
	 userValue -= 1;
   }  
}


Thanks !!!!! :)
Topic archived. No new replies allowed.