Inserting an element into an array - c++

How can I make an inset method that will add a number into the array in the correct order?
void addElement(int table[], int element, int length) {
int x = 0;
int temporary=0;
cout<<length<<endl;
if(length == 1) {
table[0] = element;
}
else {
if(length == 2) {
if (table[0] > element) {
int temp = table[0];
table[0] = element;
table[1] = temp;
}
else {
table[1] = element;
}
}
else {
for(int i = 0; i< length && x == 0; i++) {
if(element<table[i] && element>=table[i-1]) {
for(int y = i; y<length; y++) {
temporary = table[y+2];
int temp = table[y];
table[y] = element;
table[y+1] = table
}
}
}
}
}
}
This is as far as I have gotten. In my main class I have worked it out so that array is increased by 1. So there is one open space at the end of the array for everything to be pushed back by 1.

You can scan the array from back to front, moving values up until you find the correct insertion point.
void addElement(int *table, int element, int length)
{
int i = length - 1;
for (; i > 0 && table[i-1] > element; --i)
{
table[i] = table[i-1];
}
table[i] = element;
}

Write a shiftElements function, write a findIndexOfFirstGreaterThan function, then in addElement - find the index, if -1 then put in last slot, else shift elements using index, then a[index]=elem;

Draw yourself an example, then work out a list of very simple steps required to do what you want.
Then write code that does those steps.

Im not sure if this is what your looking for, but I think you want something that adds an element depending on its integer value. Also, I do not have access to a compiler at this moment so there might be a couple of errors. The code below is just written to give you a brief idea of what you could do, but probably not a perfect solution to your problem.
int addElement (int element, int array [], int length)
{
vector <int> vectorOfInts; //vector to store current order of ints
vector <int> vectorOfArrangedInts; //vector to store arranged order
for (int counter = 0; counter < length; counter ++) //loop to fill the array with values
{
vectorOfInts.push_back (array [counter]);
}
for (int counter = 0; counter < vectorOfInts.length(); counter ++) //loop through all elements
{
int temp = 0; //stores temp value of biggest number found at a specific moment
int elementIndex; //stores indexes
for (int counterTwo = 0; counterTwo < vectorOfInts.length(); counterTwo ++) //loop through all elements to find the biggest array
{
if (vectorOfInts.at (counterTwo) >= temp) //if value is bigger than current biggest number
{
temp = vectorOfInts.at (counterTwo); //change temp value
elementIndex = counterTwo; //remember index
}
}
vectorOfArrangedInts.push_back (vectorOfInts.at(elementIndex)); //add the biggest number to the arranged values
vectorOfInts.erase (vectorOfInts.begin() + elementIndex); //remove the biggest element
}

Related

Merging multiple sorted arrays using min heap

Looking to implement a function to merge multiple sorted arrays (of the same size) using STL's min heap. Here's what I have so far:
struct node{
int element; // the actual element that is being stored
int index; // array index from where the element was taken
int next; // next index
node(int x, int y, int z){
element = x;
index = y;
next = x;
}
bool operator<( const node & d ) const {
return element < d.element;
}
};
void multiway_merge(vector<vector<int> >& input_lists, vector<int>& output_list){
// n represents the number of unordered sublists and m is the number of integers comprising each sublist
size_t n = input_lists.size();
size_t m = input_lists[0].size();
int element;
vector<node> heap;
heap.reserve(m);
// loading first element of each sub-array into heap: (believe is correct)
for(int i = 0; i < n; i++){
node current(input_lists[i][0], i, 1);
heap.push_back(current);
}
make_heap(heap.begin(), heap.end());
for(int j = 0; j < (n*m); j++){
node root = heap[0];
output_list[j] = root.element;
if(root.next < m){ // if the next element isn't bigger than the array itself...
root.element = input_lists[root.index][root.next];
root.next += 1;
}
else root.element = INT_MAX; // problem is here
heap[0] = root;
make_heap(heap.begin(), heap.end());
}
}
My output is generally one of the inputted numbers and then 2147483647 (INT_MAX) for the rest of the output. I commented where/why this happens above, but overall I'm very confused on how to move within the for loop to the next element and continue going through the vectors to add more elements to the output.
Any help would be greatly appreciated!!

insertion sort algorithm using a second array C++

Trying to understand the insertion sort algorithm..
My algorithm looks like this currently:
void insertionSort(int *array, int N) {
int value;
int hole;
int *array2;
for (int i = 1; i < N - 1; i++) {
value = array[i]; //next item to be inserted in array 2
hole = i;
while (hole > 0 && array[hole - 1] > value) {
array[hole] = array[hole - 1];
hole = hole - 1;
}
array[hole] = value;
}
}
My algorithm works for sorting arrays, however I now need to change it so that I build up a new sorted array (array2) one element at a time, rather than just working with the original array.
Is there a simple way to implement this given my completed algorithm?
Thanks.
You can use the following method:
int *array2 = calloc(N, sizeof(int));
for(var index = 0; index < N; index++)
{
array2[index] = array[index];
}
and after that use array2 instead of array
then just change the prototype of your function to int *insertionSort
All remaining is to return array2 at the end of task
But be aware of memory leak: https://en.wikipedia.org/wiki/Memory_leak

How to find all possible combinations of 5 numbers in an array 0-9

I am new to C++ programming and I would like to get all the possible combinations of a one-dimensional array with 5 elements and without numbers repeating for example it starts with 00001, 00002, 00003, ... ,99999.
int count(){
while (i<100000){ //loop to go thru all possible combinations
//std::cout<<i<<"\t";
if (i>=10000){
num(i);
print();
}
i++;
}
}
void num (int i){ /* method to sort all the number to the array for i */
takeNumbersFromUser=i;
for( n=0;n<arraySize;n++){
if (control==0){
ar[n]=takeNumbersFromUser % 10;
}
else if (control==1){
temp= takeNumbersFromUser % 100;
ar[n]=temp/10;
}
else if (control==2){
temp = takeNumbersFromUser % 1000;
ar[n] = temp/100;
}
else if (control==3){
temp = takeNumbersFromUser % 10000;
ar[n] = temp/1000;
}
else if (control==4){
temp = takeNumbersFromUser % 100000;
ar[n] = temp/10000;
}
control++;
}
}
void print(){ //print out
std::cout<<"\n\n\tyou entered "<<takeNumbersFromUser<<"\n\n";
for (n=5;n>=0;n--){
std::cout<<ar[n]<<"\t";
}
}
}
Thank you.
Something like?
// Size of parent array (10^length)
int size = 100000;
// Length of number
int length = 5;
// Two dimensional array to hold the numbers
int** matrix = new int*[size];
// Create all elements in the array
for(int i=0;i<size;i++) {
matrix[i] = new int[length];
// Temporary variable to "play" with 'i'
int temp = i;
for(int j=length-1;j>=0;j--) {
matrix[i][j] = temp%10;
temp /= 10;
}
}
I believe this is very simple, and does not require further explanation.
If it does, please ask and I will provide
EDIT:
As suggested, you can replace the int* array with:
new vector<int>[size]
Then in the for j loop, there is no need to create a new array, and you can just use: matrix[i].push_back(temp%10)
And finally, to print this, you can do a new for i loop, going over the vectors array, and inside to have a foreach loop, something like:
for(int n : v)
std::cout << n << " ";
You can deffinetly should be able to manage from here.

linked list access violation writing location

I'm writing a program doing LSD radix sort with SSN. The program will parse the number into 3 digits and do 3 passes. Each pass I store the number into corresponding array element bucket[]; if there's a duplicate, I create a linked list in that location and store the duplicated one behind the one that's already there. The code breaks when I try to insert in the end of the linked list.
EDIT new error message
class node
{
public:
node(int n, node *p){data=n;next=p;}
int data;
node *next;
};
void genData(int *dta, int n)
{
for(int i=0; i < n; i++)// generate the social security numbers at random
dta[i] = rand()%889 + 111 + 1000*(rand()%889 + 111) + 1000000* (rand()%889 + 111);
}
int radixSort(int *dta, int n, int *out)
{
// the dta array contains the data to be sorted.
// n is the number of data items in the array
// out is the array to put the sorted data
node *bucket[1000]; // declare an array of 1000 linked lists (head pointers)
int count = 0; // use this to count the instructions to graph the big-o
for(int i = 0; i < n; i++)out[i] = dta[i];
for (int pass = 0; pass < 3; pass++)
{
for (int j = 0; j < 1000; j++){
bucket[j] = NULL;
}
delete bucket;
delete[]bucket;
for (int i = 0; i < n; i++){
int index=0;
switch (pass)
{
case 0:
index = out[i] % 1000;
case 1:
index = (out[i]/1000) % 1000;
case 2:
index = out[i] / 1000000;
};
if (bucket[index] = NULL){
bucket[index] = new node(out[i], NULL);
}
else{
node *cur=bucket[index];
while (cur->next!= nullptr){ //****access violation reading location
cur = cur->next;
}
node *ptr = new node(out[i], NULL);
cur->next = ptr;
}
}
int idx = 0;
for (int i = 0; i < 1000; i++){
if (bucket[i] == NULL) continue;
else{
out[idx] = bucket[i]->data;
idx++;
count++;
}
}
}
Theres a number of problems in your code:
In your switch-statement you have lines like index == out[i] % 1000;Those do a comparison and i doubt this is what you want. Assignments use single =
Your initialization for (int j = 0; j < 1000; j++){bucket[j] = NULL;} does not check if theres already a pointer in it - this will cause memory leaks after the first pass. Remember: Every new needs a delete.
And thats what is probably breaking your code: while (cur!= NULL){cur = cur->next;} exits the while-loop once cur is the nullptr - which means trying to dereference it 2 lines later is trying to dereference the nullptr and a bad idea. What you probably want to check in order to get your last element is `while(cur->next != nullptr)
And just as a note: if your compiler supports nullptr its a good idea to use it, even if you might need to enable C++11 via appropriate flags.

C++ - Ordered ArrayList

I have an ordered arrayList. Where elements are to be ordered in 1,2,3,4,5,6.
At the moment the push function is not working. It will insert an element, but there is a problem which i cannot figure out. The push will work once you insert an incremented number... So like 1,2,3,4,5 but will not work once i insert like this 5,2,4,3,2,1.
Can anyone help me with this?
Here is my code:
Initialisation
template <class Datatype>
//--------------------------------------------------------------------------------------------
// Class: OrderedArray.
//--------------------------------------------------------------------------------------------
class OrderedArray
{
//--------------------------------------------------------------------------------------------
// Member Variables.
//--------------------------------------------------------------------------------------------
private:
Datatype* m_array;
int size;
int g_size;
int num_elements;
//---------------------------------------------------------------------------------------
// Name: Print Function:
// Description: To print out all elemenst in the Array.
//---------------------------------------------------------------------------------------
void print()
{
for(int i=0;i< size;i++)
{
cout << "Position: " <<m_array[i]<<endl;
}
}
//---------------------------------------------------------------------------------------
// Name: Resize Function:
// Description: To resize the Array.
//---------------------------------------------------------------------------------------
void Resize(int p_size)//resizes the array to the size of p_size
{
if(p_size < 0)//checks if new size is less than 0
{
cout << "ERROR! Size of an array can not be less than 0!" << endl;
}
else//else its ok to continue
{
Datatype* newArray = new Datatype[p_size];//creates a pointer newArray that points at a new array
if(newArray == 0)
return;
int min;
if(p_size < m_size)//checks the if the new array is smaller than the old one
min = p_size;
else//else its going to be bigger
min = m_size;
int index;
int temp = num_elements;//puts num_elements into a temporary variable called temp
num_elements = 0;//num_elements is set to 0
for(index = 0; index < min; index++)
{
newArray[index] = m_array[index];//places everything from the old array into the new array that will fit.
if(num_elements < temp)//if the num_elements is less than temp(the original num_elements)
{
num_elements++;//increment num_elements. This will keep incrementing to create the new num_elements based the number of elements cut off in the resize
}
}
m_size = p_size;//sets the old size to be equal to the new size
if(m_array != 0)
delete[] m_array;//deletes the old array
m_array = newArray;//makes m_array point at the new array
newArray = 0;//makes newArray a null pointer
}
}
//---------------------------------------------------------------------------------------
// Name: Push
// Description:
//---------------------------------------------------------------------------------------
void push(Datatype p_item)
{
if(num_elements == size)//checks if the array is full and needs to be resized
{
Resize(size + g_size);//calls the resize function
}
int pos = num_elements;
for(int x=0;x<num_elements;x++)
{
if(p_item < m_array[x])
pos=x;
break;
}
//loops through the array from high to low moving all values to the right
//to make space for the passed in value until it gets to the right place
for(int index = num_elements; index >= pos; index--)
{
m_array[index] = m_array[index-1];//moves the values to the right
}
m_array[pos] = p_item;//the passed in value is positioned into its ordered position
num_elements++;
cout<< "Num Elements " << num_elements;
cout<< "Size " <<size;
}
I think I found the beginning of the problem:
for(int x=0;x<num_elements;x++)
{
if(p_item < m_array[x])
pos=x;
}
your pos will always always be at the end of the array that way(assuming the array is properly sorted up to that point). add a break statement to let your loop know when it should stop assigning greater and greater values to pos
for(int x=0;x<num_elements;x++)
{
if(p_item < m_array[x])
{
pos=x;
break;
}
}
your code has some other issues too, for instance
for(int index = num_elements; index > pos; index--)
{
m_array[index] = m_array[index+1];//moves the values to the right
}
actually moves the values left. change the assignment to
for(int index = num_elements; index > pos; index--)
{
m_array[index] = m_array[index-1];//moves the values to the right
}