Code

float valueToInsert = 55.55;
float[] myArray = { 2.41, 2.83, 6.47, 7.15, 12.02, 15.11, 17.72, 20.66, 
22.96, 26.49, 26.64, 33.24, 34.46, 41.93, 51.25, 53.16, 60.75, 65.87, 71.33, 
80.42, 81.78, 82.68, 84.27, 84.51, 84.62, 89.56, 93.13, 94.95, 97.91, 99.31};

// PUT YOUR CODE HERE. It should modify myArray[].

float x = 0;

for (int i = 0; i < myArray.length; i++){
  if (myArray[i] > valueToInsert){
   x = myArray[i]; //assign x to current value
  myArray[i] = valueToInsert; //clobber current value with valueToInsert
  valueToInsert = x; //re-assign valueToInsert to the previous x 
                     //so that myArray[i] > valueToInsert aren't all clobbered 
 }
}

// TEST YOUR WORK WITH THIS PRINTING CODE:
for (int i=0; i < myArray.length; i++){
  float r = myArray[i];
  print(myArray[i]);
  if (i < (myArray.length -1)){
    print(", ");
  }
}



/*
Your output should now read like this:
2.41, 2.83, 6.47, 7.15, 12.02, 15.11, 17.72, 20.66, 22.96, 26.49, 26.64, 
33.24, 34.46, 41.93, 51.25, 53.16, 55.55, 60.75, 65.87, 71.33, 80.42, 
81.78, 82.68, 84.27, 84.51, 84.62, 89.56, 93.13, 94.95, 97.91
*/

0601 - Array Manipulation: Insertion into a pre-sorted array

Statement:

// In this assignment, you are provided with an array called "myArray".
// This array contains floats which have already been sorted for you. 
// Your job is to insert a new number into this array, in the correct 
// position, such that the array is still correctly sorted afterwards.
// Your code should work with any provided number, but for this exercise,
// you are asked to insert the value: 55.55.
// 
// When you insert this new number into the array, you will need to shift
// certain pieces of data further down the array, by one index position. 
// For example, if you are asked to insert the number 55.55, then all 
// pieces of data higher than 55.55 will have to "move over" one spot. 
// For this exercise, assume that you will LOSE the last (highest) 
// piece of data -- it will get bumped out of the array into oblivion. 

float valueToInsert = 55.55;
float[] myArray = { 2.41, 2.83, 6.47, 7.15, 12.02, 15.11, 17.72, 20.66, 
22.96, 26.49, 26.64, 33.24, 34.46, 41.93, 51.25, 53.16, 60.75, 65.87, 71.33, 
80.42, 81.78, 82.68, 84.27, 84.51, 84.62, 89.56, 93.13, 94.95, 97.91, 99.31};

// PUT YOUR CODE HERE. It should modify myArray[].
// ..........................................?????

// TEST YOUR WORK WITH THIS PRINTING CODE:
for (int i=0; i < myArray.length; i++){
  float r = myArray[i];
  print(myArray[i]);
  if (i < (myArray.length -1)){
    print(", ");
  }
}

/*
Your output should now read like this:
2.41, 2.83, 6.47, 7.15, 12.02, 15.11, 17.72, 20.66, 22.96, 26.49, 26.64, 
33.24, 34.46, 41.93, 51.25, 53.16, 55.55, 60.75, 65.87, 71.33, 80.42, 
81.78, 82.68, 84.27, 84.51, 84.62, 89.56, 93.13, 94.95, 97.91
*/

hide statement