0
Help it's not sorting all negative elements
In this code if we add one positive element then it is sorting perfectly but an array full of negative elements is not sorting perfectly Edit: i have to sort element after squaring them. #include <iostream> using namespace std; int main() { int arr[5] = {-3, -2, 0 , 2 ,4}; for(int i = 0; i<5; i++){ arr[i] = arr[i] * arr[i]; } for (int i = 0; i<5; i++){ cout<<arr[i]; } for(int i = 0; i<5; i++){ for(int j = 0; j<4; j++){ if(arr[j] > arr[i]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for (int i = 0; i<5; i++){ cout<<arr[i]; } }
8 ответов
+ 2
herik Sevak then what is your expected output for the code example...? What wrong you getting there.. Can you explain more.. briefly..?
+ 1
If you are sorting array then why are you doing
for ( int i = 0; I<5; I++)
arr[I] = arr[I] * arr[I]; // remove these lines...
Note : -ve * -ve = +ve
+ 1
herik Sevak
Sry am not able to find .. !
Can you add a sample of all negetive numbers with expected output..?
+ 1
herik Sevak
you don't even have to implement your own sort. C++ can do that for you if you include <algorithm>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
//int arr[5] = {-3, -2, 0 , 2 ,4};
int arr[5] = {-3, -2, 0, -5, -2};
for (int i = 0; i<5; i++)
cout<<arr[i]<<' ';
cout<<'\n';
sort(arr, arr+5);
for (int i = 0; i<5; i++)
cout<<arr[i]<<' ';
cout<<'\n';
reverse(arr, arr+5);
for (int i = 0; i<5; i++)
cout<<arr[i]<<' ';
cout<<'\n';
}
0
why did you squared the elements ?
in first for loop .
(one suggestion : dont use c style fixed array, it will trouble you later..)
0
I can't remove squaring loop
0
Jayakrishna🇮🇳 put all negative number in array and see output it is not sorting If we insert all negative elements.
0
herik Sevak
There is an error in your inner loop. j should be j=i+1.
Also, c++ have a swap function.
#include <iostream>
using namespace std;
int main() {
//int arr[5] = {-3, -2, 0 , 2 ,4};
int arr[5] = {-3, -2, 0, -5, -2};
for (int i = 0; i<5; i++){
cout<<arr[i]<<' ';
}
cout<<'\n';
for(int i = 0; i<5; i++){
for(int j = i+1; j<5; j++){
if(arr[j] > arr[i])
swap(arr[i],arr[j]);
}
}
for (int i = 0; i<5; i++){
cout<<arr[i]<<' ';
}
}