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...
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.
To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With