Fascinating and amusing illustration of the tendency for people to herd or swarm. Raises questions about motivation and reward where people flock to follow or support a particular cause or product. People like to belong. Early adopters/pioneers are risk-takers. The swarm effect becomes part of the product's appeal. The internet and modern communications technologies accelerate and expand the phenomenon dramatically.
1/05/2013
1/02/2013
Dijkstra Shortest Path Algorithm
Velchev
January 02, 2013
12/29/2012
String Reverse using XOR
Velchev
December 29, 2012
Better implementation of string reverse is by using XOR operation. This eliminates swap operation. See how it works:
public static final String reverseWithStringBuilderBuiltinMethod(String string) {
StringBuilder builder = new StringBuilder(string);
return builder.reverse().toString();
}
The source code for this article is part of the library: Java Algorithms - Implementation.
public static final String reverseWithXOR(String string) {
char[] array = string.toCharArray();
int length = array.length;
int half = (int) Math.floor(array.length / 2);
for (int i = 0; i < half; i++) {
array[i] ^= array[length - i - 1];
array[length - i - 1] ^= array[i];
array[i] ^= array[length - i - 1];
}
return String.valueOf(array);
}
The performance of this method is very similar as the one implemented in the Java Library:
StringBuilder builder = new StringBuilder(string);
return builder.reverse().toString();
}
Reversing a string with StringBuilder built-in reverse method.
before=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz after=zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
Computed in 26000 ns
Reversing a string with swaps.
before=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz after=zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
Computed in 75000 ns
Reversing a string with XOR.
before=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz after=zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
Computed in 20000 ns
The source code for this article is part of the library: Java Algorithms - Implementation.
Subscribe to:
Posts (Atom)
