c++ - arrays not being assigned properly -
void sort(int* a,int l) { int j; int b[l]; for(int i=0;i<l;i++) { j = largest(a,l); b[l-i-1] = a[j]; a[j] = -1; } = b; } int main() { . int c[3] = {x,y,z}; ... sort(c,3); cout<<c[0]<<c[1]; }
output coming -1-1 if assign a[0] = b[0] , on, getting right answer. ps: i've tried using *a = *b, giving first element correct.
when assign a = b
, re-assign local variable holds pointer first element of array. assignment not change in main
. in particular, contents of a
not affected.
you must copy elements b
a
after have finished sorting:
void sort(int *a, int l) { int j; int b[l]; // sort temporary array b (int = 0; < l; i++) { j = largest(a, l); b[l - - 1] = a[j]; a[j] = -1; } // copy temporary array b result array (int = 0; < l; i++) a[i] = b[i]; }
but if @ it, amol bavannavar right: don't have check whole array largest element each time. enough check remaining elements. instead of assigning low value "used" elements, swap largest elements end. when that, you'll see processed elements @ end, unprocessed elements @ beginning. can sorting in place without need of temporary array:
void sort2(int *a, int l) { while (l) { int j = largest(a, l--); int swap = a[j]; a[j] = a[l]; a[l] = swap; } }
Comments
Post a Comment