Sunday, 15 July 2012

Need explanation of reversing an array in C++ from high to low -



Need explanation of reversing an array in C++ from high to low -

i beginner in c++ , may question basic not understanding point. have array {10,20,30,40,50,60,70,80,90,100}; , want print {100,90,80,70,60,50,40,30,20,10}. have below code this:

#include <iostream> using namespace std; int main() { int ara[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; int i, j, temp; for(i = 0, j = 9; < 10 && i<j; i++, j--) { temp = ara[j]; ara[j] = ara[i]; ara[i] = temp; } for(i = 0; < 10; i++) { cout<<ara[i]<<endl; } homecoming 0; }

but not sure why using && i<j in below line. if not utilize array out set comes {10,20,30,40,50,60,70,80,90,100}; want clear explanation can understand.

for(i = 0, j = 9; < 10 && i<j; i++, j--) {

the way you're doing it, you're swapping first element in array lastly element in array , working way towards them middle of array.

like array like: 1,2,3,4,5

the first iteration swap 1 , 5. sec iteration swap 2 , 4. 3rd iteration nil swapped.

at point array like:

5,4,3,2,1

in 3rd iteration = j.

if didn't have < j condition, loop continuing iterating.

the 4th iteration swap 4 , 2 again. 5th iteration swap 5 , 1 again. thus, array become:

1,2,3,4,5 again.

so < j status crucial reverse ascending array. < 10 part redundant.

side note:

its much easier utilize std::sort

c++

No comments:

Post a Comment