+ 2
Not related, but important: 1. Do use indentation. It helps a lot those wanting to read your code. 2. Don't use lots of empty lines. So many just force the reader to scroll a lot and forbid him/her to see a good chunk. Use just one between sections with distinct logical purpose.
7th Jan 2022, 1:58 AM
Emerson Prado
Emerson Prado - avatar
0
Try this. It will work. int main() { int arr[]={22,2,10,4,80,98}; int size= end(arr) - begin(arr); for(int u=0;u<size;u++) { for(int i=0;i<size;i++) { if(arr[u]<arr[i]) { swap(arr[u],arr[i]); } } } for(int i=0;i<size;i++) { cout<<arr[i]<<endl; } return 0; }
7th Jan 2022, 12:36 PM
Abraham
Abraham - avatar
0
Manav Roy Here's a bug. the last element of your array would have been swap(arr[a],arr[v-1]); as index start with 0 last element is size -1. But you wrote swap(arr[a],arr[v]);
7th Jan 2022, 4:07 PM
Abraham
Abraham - avatar
0
Manav Roy I've fixed your code!!! #include <iostream> #include <climits> using namespace std; int main() { int arr[] = {22, 2, 10, 4, 80, 98}; int size = end(arr) - begin(arr); /* always initialize variable before using in a loop */ int a = 0; int v = size; for (int u = 0; u < size; u++) { /* must declare max as local variable of the first for loop otherwise max will be 98 for the every iteration therefore the if statement fails. */ int max = INT_MIN; for (int i = 0; i < v; i++) { if (max < arr[i]) { max = arr[i]; a = i; } } /* you need to swap after max have been truly found or until the nested for loop ends otherwise it will just swap for every iteration of the nested for loop */ swap(arr[a], arr[v - 1]); --v; } for (int i = 0; i < size; i++) { cout << arr[i] << endl; } return 0; }
7th Jan 2022, 7:26 PM
Abraham
Abraham - avatar
0
Manav Roy I see. When you get used to indentation, it will be way more clear than the line breaks.
7th Jan 2022, 10:42 PM
Emerson Prado
Emerson Prado - avatar
0
Manav Roy If you don't initialize a variable, the variable value remain undefined. C/C++ initializes the variable with whatever value which was previously stored at that memory location (garbage value). Some compilers initialize this for you but it's best you do it yourself because it most likely to be problematic when used on larger projects.
8th Jan 2022, 12:25 PM
Abraham
Abraham - avatar