Ali
Ali

Reputation: 5476

C++: A Basic Array Swap

I simply could not understand why the following code does not work. What could be the possible reason that the swap operation does not work;

#include <iostream>

using namespace std;

void rotateK(int* arr, int start, int finish) {
    int temp;
    for(int i=0;i<=finish;i++) {
        temp=arr[i];
        arr[i]=arr[finish-i];
        arr[finish-i]=temp;
    }
    for(int i=0;i<=finish;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
}


int main(){
    int arr[5]={1,2,3,4,5};
    rotateK(arr,0,4);
    return 0;

}

Upvotes: 1

Views: 958

Answers (2)

unkulunkulu
unkulunkulu

Reputation: 11912

You're swapping elements twice. You can consider this idea of flipping a segment of an array.

int i = start;
int j = finish;
while( i < j ) {
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    ++i; --j;
}

It's difficult to make a mistake if you write it like this.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258598

It does work (although not how you want it to work). But swaps the elements twice, that's why the processed array is identical to the original one.

You probably want:

for(int i=0 ; i<=finish/2 ; i++)

or even

for(int i=start;i<=(finish-start)/2 + start;i++)

so that you actually use start.

Upvotes: 9

Related Questions