Skip to content

Instantly share code, notes, and snippets.

@sampottinger
Created March 1, 2013 04:57
Show Gist options
  • Save sampottinger/5062572 to your computer and use it in GitHub Desktop.
Save sampottinger/5062572 to your computer and use it in GitHub Desktop.
Shows how to insert into an array in C
/**
* Inserts a value into an array, shifting elements over as needed.
*
* @param target: The array to insert into.
* @param index: The index to insert the new element into.
* @param newVal: The value to insert.
* @param targetSize: The size of the array before inserting the new element.
* Not capacity, the number of existing elements.
* @warn Does not check that the array is large enough to hold the new element.
**/
void insert_into_array(int * target, int index, int newVal, int targetSize)
{
for(int i=targetSize+1; i>index; i--)
target[i] = target[i-1];
target[index] = newVal;
}
/**
* Finds the location that a new value should be inserted at to keep the array sorted.
*
* @param target: The array the value is being inserted into.
* @param newVal: The value to be inserted.
* @param targetSize: The size of the array before inserting the new element.
* Not capacity, the number of existing elements.
* @return The index at which the value should be inserted.
* @warn Does not check that the array is large enough to hold the new element.
**/
int find_insert_point(int * target, int newVal, int targetSize)
{
int i;
for(i=0; i<targetSize; i++)
{
if(target[i] > newVal)
return i;
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment