How to sort 5 items using only 7 comparisons
I am very interested in how to sort 5 items using only 7 comparisons. I think I understand the theory how to do it but unfortunately I'm not able to write it as a code. Here I found an example in LISP
I really tried to understand it but it seems to me be not working. For example on the numbers 5,4,3,2,1.
Could anybody please give me an example code, but not in LISP? I prefer Java or C/C++. It would rea开发者_StackOverflow社区lly help me in school.
Thank you in advance
P.S. Sorry for my english
Edit: Here I add some piece of code I wrote in Java. Variables a,b,c,d,e are there only for my better orientation in code. I'm able to write specific code for specific input items, that's no problem. But I can't write general code.
public static void sort(int p[]) {
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int e = 4;
if (p[a] > p[b]) {
swap(p,a,b);
}
if (p[c] > p[d]){
swap(p,c,d);
}
if (p[b] > p[d]){
swap(p,b,d);
}
if (p[e] < p[b]) {
if (p[e] < p[a]) {
swap(p,a,e);
swap(p,d,e);
//swap(p,b,d);//BLBE
}else{
swap(p,b,e);
swap(p,d,e);
}
}else {
if (p[e] < p[d]) {
swap(p,d,e);
}
}
if (p[c] < p[b]) {
if (p[c] < p[a]) {
swap(p,a,c);
swap(p,b,c);
}else
{
swap(p,c,b);
}
}else {
if (p[c] > p[d]) {
swap(p,d,c);
}
}
}
Writing a general comparison-based sorting algorithm takes O(n lg n) comparisons. If I'm not mistaken, then all O(n lg n) sorting algorithms will sort 5 items in about 7 comparisons. Mergesort, Heapsort and Quicksort if you're lucky.
精彩评论