c++ - Why it doesn't swap two integers in an array? -


#include <iostream> using namespace std; int main() {     int a[6]={3,7,9,4,6,1};     int max;     max = a[0];     for(int i=0; i< 6; i++)     {         if(a[i] > max)         {             max = a[i];         }      }     //cout << max <<"\n";      int temp;     temp=a[0];     a[0]=max;     max = temp;      for(int i=0;i<6;i++)     {         cout << a[i] << endl;     }     return 0; } 

i want swap maximum value first 1 in decared array replaces 1st value maximum while maximum value retained @ position.

the logic wrong. swapping values of variable max instead of element max value.

if want swap element max value, keep track of position, this:

 if(a[i] > max)     {         max = a[i];         pos = i;     } 

and while swapping, use follows:

int temp; temp=a[0]; a[0]=a[pos]; a[pos] = temp; 

note: alternative way use pointers, simple non-pointer method.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -