How do i implement bubblesort and where [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The task is to implement a bubblesort function followed by a linearsearch aka "linsok" in my "familj" array. the array keeps both the name and the age, so i want to sort the array after their age and print it out. ive got the line search to work but now im stuck with the bubblesort.
The problem is that i dont know how to make my bubble sort code work for this code.
so do i implement the second piece of code in this?
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string namn;
int alder;
void skrivUt(string _namn, int _alder)
{
namn = _namn;
alder = _alder;
}
};
int linsok(Person* PersonArray, int key)
{
for (int i = 0; i < 4; i++)
{
if (PersonArray[i].alder == key)
return i;
}
return -1;
}
int main()
{
Person familj[4];
familj[1].skrivUt("Emma",23);
familj[3].skrivUt("Emilia",29);
familj[2].skrivUt("Johan",26);
familj[0].skrivUt("Timmy ",21);
int index = linsok(familj,22); //the age of the person im looking for.
if(index== -1)
cout << "Personen hittades ej!"; //person not found
else
//prints out the persons name and the index.
cout << "Personen heter " << familj[index].namn << " hen finns på index " << index << endl;
cin.get();
return 0;
}
This is the piece of bubble-sort code i used before and it works.
int p [] = {10,56,73,23,31,24,43};
int a = 6;
for (int i = 0; i < a; i++)
{
int nrLeft = a - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j] > p[j+1])
{
int temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
for(int i = 0; i < 7; i++)
cout << p[i] << endl;
cin.get();

It's likely that you want to convert this to a function that you pass your array of Person objects to, along with the size of it, and then you just access the part that you want to compare. Since you'd be implementing it as a function, you can use it in the same way you use your linsok function, although you'd probably want it to return the sorted array as opposed to an index.
Disclaimer for following code: Neither run nor compiled
Person* bubbleSort(Person* p, int size)
{
for (int i = 0; i < size; i++)
{
int nrLeft = size - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j].alder > p[j+1].alder)
{
Person temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
return p;
}
That's based off you sorting them by alder (which I guess is age? I don't speak Swedish(?)) You just need to provide the signature, and alter it based on your needs, but the basic idea is that you just change what you compare, and the data types.
Another way to do this is to return an int or void(But you should return an int to tell you if it was successful or not), and pass a pointer to the array, so Person** in the signature, and operate directly on that array, but that's a little more difficult, and arguably bad practice, depending on use case.

Related

C++ delete duplicates from cstring [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a c-string that looks something like ABBBCACACACBA and I'm supposed to create a function that deletes the duplicate characters so I end up with ABC. I created a nested for loop that replaces every letter that matches the letter in the outer loop with a \0 and increments a counter that keeps track of the repeats. I'm getting -1 as the amount of repeats that should be documented, and from checking it spits out ABBC instead of ABC. I'm stumped, any ideas?
for (int i = 0; i < SIZE; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (letter[i] == letter[j])
{
letter[j] = '\0';
repeatCounter++;
}
}
}
It is not enough to just replace duplicates with '\0', you have to actually remove them from the string and shift the remaining characters down. Try something more like this:
int size = SIZE, i = 0;
while (i < size)
{
int j = i + 1;
while (j < size)
{
if (letter[j] == letter[i])
{
for (int k = j + 1; k < size; k++)
{
letter[k-1] = letter[k];
}
letter[--size] = '\0';
repeatCounter++;
continue;
}
j++;
}
i++;
}
Live Demo
Here's a simple example which does what you want. It uses std::string to store the output. You can copy-n-paste the code here to test and run. Look into using std::string as it has functions which will make your life easy.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input("ABBBCACACACBA");
string output;
for(size_t i = 0; i < input.size(); i++)
{
if(output.find(input[i]) == string::npos)
{
output += input[i];
}
}
cout << "Input: " << input << endl;
cout << "Output: " << output << endl;
return 0;
}

Is it possible to have functions run off the string within a variable rather than the variable name itself in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Its kind of hard to describe, but I'm basically asking whether or not I can have a function calling myString and actually have the string within get put into the function.
My code so far is:
for(uint n = 0; n < 5; n++) {
int r = n * n;
std::string R = std::to_string(n);
std::string currentSquared = ("Squared" + R);
int currentSquared.c_str() = r;
}
I know it's wrong I'd like the output to be a set of variables like:
Squared1 = 1, Squared4 = 16.
Any help would be appreciated.
No, you can't create arbitrary variables like you described, besides variable names are used during compilation and debugging, if you compile without debug symbols they disappear completely.
What you need here is to use an appropriate data structure to hold your data, instead of creating more variables to work with, you can read more about standard library containers here.
I would suggest using std::vector in your case.
std::vector<int> numbers{};
numbers.reserve(10);
for(int i = 0; i < 10; ++i) {
numbers.push_back(i * i);
}
std::cout << "Numbers squared:\n";
for (std::size_t i = 0; i < numbers.size(); ++i) {
std::cout << i << '*' << i << " = " << numbers[i] << '\n';
}
std::vector will take care of storing all the data for you, and should be your 1st choice as a container most of the time.
If you would like a dictionary that would allow you to index element with let's say std::string or const char*, you could also use a std::map.
You can take the help of std::unordered_map to create keys and gather data from them:
#include <iostream>
#include <unordered_map>
int main(void) {
std::unordered_map<std::string, int> variables;
// Initializing the map with their respective required keys
for (int i{1}; i <= 10; i++)
variables["Squared" + std::to_string(i)] = i * i;
// Displaying one of the initialized key
std::cout << variables["Squared4"];
return 0;
}
As a result, it'll display your desired output:
16 // 'Squared4' key holds (4 * 4) = 16
int main() {
vector<string> mystring;
for (int n = 0; n < 5; ++n) {
int squared = n * n;
string str_squared = to_string(squared);
mystring.push_back(str_squared);
}
for (int j = 0; j < mystring.size(); ++j) {
cout << mystring[j] << endl;
}
return 0;
}
I would try to store my strings in a container. In this instance, I used a vector. This allows me to have a set of strings, that are n squared. To display them I can iterate through my vector in the for loop. Not sure if this is what you were trying to achieve from your question.

Is this the correct implementation of Insertion Sort? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
OUTPUT
#include <iostream>
using namespace std;
int main()
{
//declaring the size of array and taking input from the user
int n = 0;
cout<<"Enter the Number of elements you want in the Array : ";
cin>>n;
//checking the user input
if(n <= 0)
{
cout<<"Not Possible\n";
return 1;
}
//declaring array of size 'n' and taking input from user
int list[n];
cout<<"Enter the Elements of the array of size "<<n<<" : ";
for(int i = 0; i < n; i++)
cin>>list[i];
//Insertion Sort
int swap = 0; //number of swaps
int comp = 0; //number of comparison
int temp; //temporary variable
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(list[j] < list[j-1])
{
//swapping equivalent to shifting
temp = list[j-1];
list[j-1] = list[j];
list[j] = temp;
comp++;
swap++;
}
else
{
comp++;
break;
}
}
//printing the iteration
cout<<"Iteration "<<(i+1)<<" : ";
for(int k = 0; k < n; k++)
cout<<list[k]<<" ";
cout<<"\n";
}
cout<<"\nSwap : "<<swap<<"\n";
cout<<"Comparison : "<<comp<<"\n";
cout<<"Sorted Array : ";
for (int i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
return 0;
}
Is this implementation of insertion sort correct because I have seen many implementation online using while loop and other things?
If not can you point out what is wrong?
Thanks in advance
link - https://github.com/ish-u/DiscreteStructures/blob/master/InsertionSort.cpp
No, this is a different type of sort, known as bubble sort. It still sorts, but insertion sort works in a different way, by keeping the array sorted at all times (moving elements if a new insertion would break the ordering).
So instead of just tagging new elements to the end of the array where you read them from cin, you should place each element directly in the right spot in the array. This will likely involve moving existing elements in order to keep the array sorted.
Note that your line
int list [n];
is wrong; you cannot allocate memory this way (and I'm surprised it even compiles). A better choice would be to use std::vector.

Removing more than one element from an array and creating a dynamic array c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm still new to c++ so this is a learning process for me. Also i know that i should initially use a vector to do this but i have an exercise that specifies an array so i'm trying to write a function that removes all duplicate elements in an array but i receive the error
C2100: illegal indirection
if someone could point me in the right direction
int main()
{
int *t;
int removel[9] = { 1, 1, 1, 2, 3, 4, 5, 6, 6, };
t = removeAll(removel, 9, 1);
for (int i = 0; i < 8; i++)
cout << t[i] << " ";
}
int* removeAll(int list[], int listlength, int removeitem)
{
int count = 0;
int* list2;
int removeindex;
int length;
int tempindex;
for (int i = 0; i < listlength; i++)
{
if (removeitem == list[i])
count++;
}
length = listlength - (count + 1);
list2 = new int[length];
int j;
while (j<=length)
{
remove_if(list[0], list[listlength - 1], removeitem);
for (j = 0; j < length; j++)
if (list[j] == NULL)// not sure what the remove_if func puts inplace of the removed element
continue;
else
list2[j] = list[j];
}
return list2;
}
Firstable you should calculate length like listlength - count, not listlength - (count + 1).
Then, after list2 = new int[length]; you should copy elements which are different with removeitem and skip other ones. You can do it like this
int j = 0;
for (int i = 0; i < listlength; i++) {
if (removeitem == list[i])
continue;
list2[j] = list[i];
j++;
}
and return successfully created list2. But you should also know its size. You can do it by creating int tSize in main and pass it to removeAll by link. removeAll will change its value to length. So add int & list2size to the parameters list of removeAll and write list2size = length; before returning list2. Finally, when printing t, change i < 8 to i < tSize.
If you do all this program will work right but don't forget about formatting.

C++ program cant find mistake [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
this program creates random number array where elements wit arguments 1,3,5,7...,19 are negative and this program should find biggest negative element but when l test program it writes some random number (6784345 instead of array element) can you help me find mistake ?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
int main()
{
int a[20],nn,i;
srand(time(0));
for(i=0;i<20;i++)
{
if(i%2==0) a[i]=rand()%(61);
else
a[i]=(rand()%(61))*(-1);
}
printf("Formirani niz je:\n");
for(int i=0;i<20;i++)
{
printf("\ "); printf("%d",a[i]);
}
najneg(a,&nn);
printf("\n\nNajveci negativni clan niza je:%d\n",nn);
return 0;
}
In this code, …
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
you forgot to dereference the pointers,
void najneg(int *pa,int *nn)
{
*nn=0;
for(int i=0;i<20;i++)
{
if(*(pa+i)<*nn) *nn=*(pa+i);
}
}
The most important fix for this function is to change its name to something readable and self-descriptive, with no arbitrary shortenings. When choosing names, think about making the calling code readable and clear. So E.g., najneg → most_negative_value_in.
Secondly, instead of logical out-argument, use the function return value.
Third, if the function doesn't need to change data, use const to let it offer a guarantee that it won't change the data.
Fourth, avoid magic numbers like 20: pass the array size as argument.
This, plus some purely cosmetic changes, yields:
int most_negative_number_in(int const* const a, int const size)
{
int n=0;
for(int i=0; i<size; ++i)
{
if(a[i]<n) { n = a[i] };
}
return n;
}
This function should be
void najneg(int *pa,int *nn)
{
*nn=0; //As you want to modify nn.
for(int i=0;i<20;i++)
{
if(pa[i]<*nn) *nn=pa[i]; //Here, you want to compare values and swap them. Not just address.
}
}
Do not try to complicate it.
In addition to what others have pointed out:
You can simplify the content of your for loops:
for(i = 0; i < 20; i++)
{
// The array slot is assigned a random value
// whether the index is positive or negative.
a[i] = rand() % 61;
// If the index is odd, change the value
// to a negative number.
if(i % 2 == 1)
{
a[i] *= -1;
}
}
In the next loop, you should combine into one printf call:
for(int i = 0; i < 20; i++)
{
printf("\ %d", a[i]);
}
Also, what is "\ " in the format specifier, a tab or a space?