Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to sort two arrays (the first one, ascending; and the 2nd one descending)
Here goes the code where the sorting is done: -
for(int i=0;i<10;i++) //1st array, ascending
{
for(int j=0;j<10;j++)
{
if(array1[j]>array1[j+1])
{
int temp=array1[j];
array1[j]=array1[j+1];
array1[j+1]=temp;
}
}
} //Over
for(int i=0;i<10;i++) //2nd, descending
{
for(int j=0;j<10;j++)
{
if(array2[j]<array2[j+1])
{
int temp=array2[j];
array2[j]=array2[j+1];
array2[j+1]=temp;
}
}
} //Over
When I try printing these, it screws up somewhere and I'm unable to pinpoint the problem in the code. Thanks..
You can use C++ itself to sort (quite efficiently) arrays, using any valid rule you want. If you want it in ascending order, you can use the default variety, which automatically uses < effectively. If you want it in descending order, you just have to use the opposite comparison, the >.
Example:
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
vector<int> makeAscending = {3,2,1};
vector<int> makeDescending = {4,5,6};
sort(begin(makeAscending), end(makeAscending)); // could pass less<int>() if you wanted
sort(begin(makeDescending), end(makeDescending), greater<int>());
// print to see answer
copy(begin(makeAscending), end(makeAscending), ostream_iterator<int>(cout, " "));
cout << endl;
copy(begin(makeDescending), end(makeDescending), ostream_iterator<int>(cout, " "));
}
Just to be precise, a valid rule for sorting is one that produces a weak ordering of the items in the container. The Wikipedia page has the rules, but they are mostly this (calling any general "rule" the symbol < and x,y,z are items in your container):
1.) x < x is never true.
2.) If x < y is true that means y < x is false. (and if x < y is false and y < x is false, they are seen as "equal")
3.) if x < y is true and y < z is true then x < z is true.
Just had to limit the inner loop to <9.
The fixed code:
for(int i=0;i<10;i++) //1st array, ascending
{
for(int j=0;j<9;j++)
{
if(array1[j]>array1[j+1])
{
int temp=array1[j];
array1[j]=array1[j+1];
array1[j+1]=temp;
}
}
} //Over
for(int i=0;i<10;i++) //2nd array, descending
{
for(int j=0;j<9;j++)
{
if(array2[j]<array2[j+1])
{
int temp=array2[j];
array2[j]=array2[j+1];
array2[j+1]=temp;
}
}
} //Over
Thank you guys!
Related
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 7 months ago.
Improve this question
In the code below I am trying to return an array containing the longest strings of the inputArray. However, when I use it the array outputted is empty.
vector<string> solution(vector<string> inputArray) {
int highestSize, add;
vector<string> newArray{};
for (int i = 0; i < inputArray.size(); ++i) {
highestSize = max(int(inputArray[i].length()), highestSize);
}
for (int i = 0; i < inputArray.size(); ++i) {
if (inputArray[i].length() == highestSize) {
newArray[add] = inputArray[i];
++add;
}
}
return newArray;
}
There are several issues in your code:
highestSize and add are not initialized. In C++ variables are not default initialized to 0 as you might have expected.
newArray is default constructed to have 0 elements. In this case you cannot use operator[] the way you did. operator[] can access only elements that were allocated. You can use push_back to add to the vector. If your code was changed so that you knew in advance how many entries you will need in newArray, you could also resize the vector and then use operator[] to access the elements. There are some more options like resereving capacity and using push_back, you can see more info here.
It's better to pass inputArray by const& to avoid an unneeded copy.
A fixed version:
#include <string>
#include <vector>
std::vector<std::string> solution(std::vector<std::string> const & inputArray) {
int highestSize{ 0 };
std::vector<std::string> newArray{};
for (int i = 0; i < inputArray.size(); ++i)
{
highestSize = std::max(int(inputArray[i].length()), highestSize);
}
for (int i = 0; i < inputArray.size(); ++i)
{
if (inputArray[i].length() == highestSize)
{
newArray.push_back(inputArray[i]);
}
}
return newArray;
}
A side note: it's better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My solution to a HackerRank problem works but times out when very large amounts of data are used, such as the following: https://hr-testcases-us-east-1.s3.amazonaws.com/9403/input11.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1565703339&Signature=JcuoWT7wKxpU3GWudO4wLNWK6Dg%3D&response-content-type=text%2Fplain
I'm quite aware that the code is far from ideal, and will probably make experienced software developers cringe... so I'm hoping it can be improved.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
cin >> N;
vector<int> v;
vector<string> s;
for (int i = 0; i < N; i++) {
int a;
cin >> a;
v.push_back(a);
}
int Q;
cin >> Q;
for (int i = 0; i < Q; i++) {
int a;
int b = 0;
cin >> a;
for (int j = 0; j < v.size(); j++) {
if(v[j]==a) {
s.push_back("Yes " + to_string(j+1));
b++;
j=v.size();
}
}
if (b==0) {
vector<int>::iterator low;
low = std::lower_bound(v.begin(), v.end(), a);
int d = low-v.begin();
d++;
s.push_back("No " + to_string(d));
}
}
for (int i = 0; i < s.size(); i++) {
cout << s[i] <<"\n";
}
return 0;
}
The problem statement is:
Ideally, I'd rather not have a completely new solution, but rather get some help making this one better.
First of all, it is always useful to analyze the performance of a software by profiling it with the adeguate tool, see here.
With just taking a look at is, there are a few points which you could optimize:
the s list is useless. You push back data on it and then print in order. Just print directly. You would save memory and the last for loop.
inside your second loop you first perform a linear search and then, if nothing is found, you use std::lower_bound which has logarithmic complexity. You could reduce the time by just looping once and looking for the element or the smallest one at the same time, reducing the amount of looping you need. You can also take advantage of the fact that the N integers are sorted to stop the search earlier.
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
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...
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 8 years ago.
Improve this question
intent is to create an array of random numbers, and sort them in ascending order
array is created, but sorting does not work (numbers are printed in random order)
have i incorrectly applied sorting by reference?
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
void mySort(long x[])
{
long min(0), temp(0), minPosition(0), i(0), j(0);
min = x[0];
for (j = 0; j < 10; j++)
{
for (i = j; i < 10; i++)
{
if (x[i] < min)
{
min = x[i];
minPosition = i;
}
}
temp = x[minPosition];
x[minPosition] = x[j];
x[j] = temp;
}
}
int main()
{
long *myArray = new long[10];
int i(0);
srand((unsigned int)time(NULL));
for (i = 0; i < 10; i++)
{
myArray[i] = rand()%11;
}
mySort(myArray);
for (i = 0; i < 10; i++)
{
cout<<'['<<myArray[i]<<']'<<endl;
}
return 0;
}
One thing that stands out is that you need to reset min and minPosition every time your outer loop kicks off. At the moment, things will go badly wrong from the second iteration onwards.
Also, be aware that this (selection sort) is a rather inefficient way to sort a list. It runs in O(n^2) time, rather than O(n log n), which is what good sorting algorithms do (Quicksort, Heapsort, Mergesort).
Well if you dont know how to sort ...you can use sort() function as
// sort() Example using arrays.
#include <iostream>
#include <algorithm>
using namespace std;
const int SIZE = 7;
int main()
{
int intArray[SIZE] = {5, 3, 32, -1, 1, 104, 53};
//Now we call the sort function
sort(intArray, intArray + SIZE);
cout << "Sorted Array looks like this." << endl;
for (size_t i = 0; i != SIZE; ++i)
cout << intArray[i] << " ";
return 0;
}
Found in ~ #include <algorithm>
Parameter 1 myvector.begin() ~ The first parameter is where you will be putting a iterator(Pointer) to the first element in the range that you want to sort. The sort will include the element that the iterator points to.
Parameter 2 myvector.end() ~ The second parameter is almost like the first but instead of putting a iterator to the first element to sort you will be putting a iterator to the last element. One very important difference is that the search won’t include the element that this iterator points to. It is [First,Last) meaning it includes the first parameter in the sort but it doesn’t include the second parameter in the sort.
Parameter 3 myCompFunction() Optional ~ The third parameter is used to define how you do the search. For example if you have a struct that has 3 different variables in it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have an exercise for sort an array in c++. I'm coding with command line programming from turbo c++.
You can use this code, it uses bubble sort algorithm.
#include <stdio.h>
#include <iostream>
using namespace std;
void sort(int *,int);
int main()
{
int arr[10] = {2,3,4,12,5,0,2,5,1,20};
sort(arr,10);
for(int i = 0;i<10;i++)
cout << arr[i] << " ";
return 0;
}
void sort(int * ar,int length)
{
for(int i = 0;i<length;i++)
{
for(int j = i;j<length;j++)
{
if(ar[j] < ar[i])
{
int swap = ar[i];
ar[i] = ar[j];
ar[j] = swap;
}
}
}
}
EDIT:
As I said it's based on the bubble algorithm. It sequentially checks the indexes from first one to last one and automatically puts the smallest number in first place, second smallest in second place and so on. You can see here or here for more information.
Here is how i did it. Hope this is what you mean.
Read the command line arguments
Convert the string to integer using atoi function
Sort using any sorting algorithm (bubble sort used here)
Print the result
To see how bubble sort works check out this.
#include<iostream.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i,j,temp, arr[10];
for(i=1; i<argc; ++i)
{
arr[i-1] = atoi(argv[i]);
}
/* Sort the array using bubble sort alogrithm */
for(i=0; i<argc-2; ++i)
{
for(j=0; j<argc-2; ++j)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
/* Print the result */
cout<<"Sorted array : ";
for(i=0; i<argc-1; ++i)
{
cout<<" "<<arr[i];
}
return 0;
}