Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make swap function faster in c++ ?

I am writing a couple string sort algorithm with c++ and I wonder if I can make this swap operation faster.

void swap(string *items,int a, int b ){
        string temp;
        temp = items[a];
        items[a] = items[b];
        items[b] = temp;
}

I'll be appreciate if you can help...

like image 351
ibrahim Avatar asked Nov 24 '11 19:11

ibrahim


People also ask

What is the complexity of swap?

Complexity. For arrays the function has N complexity as the operation of swapping is individually performed on each element. For non array the function has constant complexity.

Is there a swap function in C?

To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

How does XOR swap work?

In computer programming, the exclusive or swap (sometimes shortened to XOR swap) is an algorithm that uses the exclusive or bitwise operation to swap the values of two variables without using the temporary variable which is normally required.


2 Answers

String class has its own swap function.

items[a].swap(items[b]);

It's the fastest way to do this because it accesses the string internals and avoids all copying.

See here.

like image 61
Antti Huima Avatar answered Oct 20 '22 18:10

Antti Huima


You can use std::swap():

void swap(string *items, int a, int b) {
    std::swap(items[a], items[b]);
}

But there's no guarantee that this will be measurably faster, and this probably isn't the slow part of your code anyway. Have you measured the performance of the swap operation compared to the rest of your code?

like image 33
Greg Hewgill Avatar answered Oct 20 '22 17:10

Greg Hewgill