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
Post a Comment