Created
March 1, 2013 04:57
-
-
Save sampottinger/5062572 to your computer and use it in GitHub Desktop.
Shows how to insert into an array in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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