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]; } }

5th Sep 2022, 12:05 PM
herik Sevak
8 Antworten
+ 2
herik Sevak then what is your expected output for the code example...? What wrong you getting there.. Can you explain more.. briefly..?
5th Sep 2022, 3:31 PM
Jayakrishna 🇮🇳
+ 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
5th Sep 2022, 12:32 PM
Jayakrishna 🇮🇳
+ 1
herik Sevak Sry am not able to find .. ! Can you add a sample of all negetive numbers with expected output..?
6th Sep 2022, 7:57 AM
Jayakrishna 🇮🇳
+ 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'; }
6th Sep 2022, 10:15 AM
Bob_Li
Bob_Li - avatar
0
why did you squared the elements ? in first for loop . (one suggestion : dont use c style fixed array, it will trouble you later..)
5th Sep 2022, 12:32 PM
Prashanth Kumar
Prashanth Kumar - avatar
0
I can't remove squaring loop
5th Sep 2022, 3:07 PM
herik Sevak
0
Jayakrishna🇮🇳 put all negative number in array and see output it is not sorting If we insert all negative elements.
5th Sep 2022, 5:02 PM
herik Sevak
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]<<' '; } }
6th Sep 2022, 4:40 AM
Bob_Li
Bob_Li - avatar