Sunday, October 16, 2011

Comparing Quick and Heap Sorts

Empirical studies show that generally quick sort is considerably faster than heapsort.
The following counts of compare and exchange operations were made for three different sorting algorithms running on the same data:
n Quick Heap Insert
ComparisonExchange ComparisonExchange ComparisonExchange
100 7121482,8425812,595899
200 1,6823289,7361,36610,3073,503
500 5,10291953,1134,04262,74621,083
Thus, when an occasional "blowout" to O(n2) is tolerable, we can expect that, on average, quick sort will provide considerably better performance - especially if one of the modified pivot choice procedures is used.
Most commercial applications would use quicksort for its better average performance: they can tolerate an occasional long run (which just means that a report takes slightly longer to produce on full moon days in leap years) in return for shorter runs most of the time.
However, quick sort should never be used in applications which require a guarantee of response time, unless it is treated as an O(n2) algorithm in calculating the worst-case response time. If you have to assume O(n2) time, then - if n is small, you're better off using insertion sort - which has simpler code and therefore smaller constant factors.
And if n is large, you should obviously be using heap sort, for its guaranteed O(nlog n) time. Life-critical (medical monitoring, life support in aircraft and space craft) and mission-critical (monitoring and control in industrial and research plants handling dangerous materials, control for aircraft, defence, etc) software will generally have a response time as part of the system specifications. In all such systems, it is not acceptable to design based on average performance, you must always allow for the worst case, and thus treat quicksort as O(n2).
So far, our best sorting algorithm has O(nlog n) performance: can we do any better?
In general, the answer is no.
However, if we know something about the items to be sorted, then we may be able to do better.
But first, we should look at squeezing the last drop of performance out of quicksort.

Thursday, October 13, 2011

Dropping Eggs from a Building


You stand before a 100-story building with two eggs. Using only these two eggs, you must figure out the highest floor from which you can drop an egg such that the egg won't break when it hits the ground (we'll call this the "highest safe floor"). Every floor is equally likely to be the highest safe floor, including the top floor, and it's also just as likely that the egg will break from every floor. You can assume that if you drop an egg and it doesn't break, its shell is just as strong as it was before you dropped it.
If you want to minimize the expected number of drops you have to perform, what strategy should you use for picking which floors to drop the eggs from? You should write a program to solve this problem.

Why some C++ operator can't be overloaded


Although most operator can be overloaded. You can't overload the C operators . and ?: (and sizeof). And you can't overload the C++ operators :: and .*. You can overload everything else :)

Let us have a brief look what the Bjarne stroustrup has suggested about it:


why can't I overload dot, ::, sizeof, etc. ?

Most operators can be overloaded by a programmer. The exception are 
. (dot)  ::  ?:  sizeof
There is no fundamental reason to disallow overloading of ?:. I just didn't see the need to introduce the special case of overloading a ternary operator. Note that a function overloading expr1?expr2:expr3 would not be able to guarantee that only one of expr2 and expr3 was executed.Sizeof cannot be overloaded because built-in operations, such as incrementing a pointer into an array implicitly depends on it. Consider:
X a[10];
 X* p = &a[3];
 X* q = &a[3];
 p++; // p points to a[4]
  // thus the integer value of p must be
  // sizeof(X) larger than the integer value of q
Thus, sizeof(X) could not be given a new and different meaning by the programmer without violating basic language rules.In N::m neither N nor m are expressions with values; N and m are names known to the compiler and :: performs a (compile time) scope resolution rather than an expression evaluation. One could imagine allowing overloading of x::y where x is an object rather than a namespace or a class, but that would - contrary to first appearances - involve introducing new syntax (to allow expr::expr). It is not obvious what benefits such a complication would bring.
Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:
class Y {
 public:
  void f();
  // ...
 };

 class X { // assume that you can overload .
  Y* p;
  Y& operator.() { return *p; }
  void f();
  // ...
 };

 void g(X& x)
 {
  x.f(); // X::f or Y::f or error?
 }
This problem can be solved in several ways. At the time of standardization, it was not obvious which way would be best. For more details, see D&E.


Sunday, October 9, 2011

Introsort

Introsort, or introspective sort is a sorting algorithm that initially uses quicksort, but switches to heap sort if the depth of the recursion is too deep to eliminate the worst-case, and uses insertion sort for small cases because of its good locality of reference.
This algorithm has a worst-case optimal running time of O(nlogn).

Wednesday, October 5, 2011

ioctl in Linux


Introduction of ioctl( )

Input/output Control (ioctl, in short) is a common operation, or system call, available in most driver categories. It is a ‘one bill fits all’ kind of system call.  If there is not other system call that meets a particular requirements, the ioctl () is the one to use. Practical examples include volume control for an audio device , display configuration for a video device, reading device registers, and son on –basically, anything to do with enough for any kind of operation ( for example, for debugging a driver by querying driver data structures). The question is: how can all this are achieved by single function prototype? The trick lies in sung its two key parameters: command and argument. The command is a number representing an operation. The argument is the corresponding parameter for the operation. The ioctl() function implementation does a ‘switch  ... case’ over the command to implement the corresponding functionality. The following has been its prototype in the Linux kernel for quite some time:
int ioctl(struct inode *I, sturct file *f, unsigned int cmd, unsigned long arg);

However, from kernel 2.6.35, it change to:

Long ioctl (struct file *f, unsigned int cmd, unsigned long arg);

                If there is a need for more arguments, all of them are put in a structure, and a pointer to the structure, and a pointer to the structure becomes the ‘one’ command argument. Whether integer or pointer, the argument is take as a long integer in kernel-space, and accordingly type-cast and processed.

Ioctl () is typically implemented as part of the corresponding driver, and then an appropriate function pointer is initialized with it, exactly as with other system call like open (), read (), etc.  For example, the character drives, it is the ioctl or unlocked ioctl (since kernel 2.6.35) function pointer field in the struct file_operations that is to be initialized.
Again, lik other system calls, it can be equivalently invoked from user-space using the ioctl() system call, prototyped in <sys/ioctl.h> as:
int ioctl(in fd, int cmd, …);

                Here, cmd is the same as what is implemented in the driver’s ioctl (), and the variable argument construct(…) is a hack to be able to pass any type of argument ( thought only one) to the driver’s ioctl(). Other parameters will be ignored.


Querying driver –internals variables

To better understand the boring theory explained below, here’s the code set for the ‘debugging a driver’ example mentioned earlier. This driver has three static global variables status, dignity, and ego, which need to be queried and possibly operated from an application. The header and query_ioctl.h defines the corresponding commands and command argument type. A listing follows:

#ifndef QUERY_IOCTL_H
#define QUERY_IOCTL_H
#include<linux/ioctl.h>
typedef struct
{
                int status, dignity, ego;
}query_arg_t;
#define QUERY_GET_VARIABLES _IOR(‘q’, 1, query_arg_t *)
#difine QUERY_CLR_VARIABLES _IO(‘q’, 2)
#endif

                Using these, the driver’s ioctl() implementation in query_ioctl.c  would be as fllows:

static int status =1, dignity=3, ego=5;

#if (LINUX_VERSION_CDE < KERNEL_VERSION(2,6,35))
static int my_ioctl(struct inode *I, struct file *f, unsigned int cmd, unsigned long arg)
#else
Static long my_ioctl(struct file *f, unsigned int cmd,unsigned long arg)
#endif
{
                query_arg_t q;
switch (cmd)
{
                Case QUERY_GET_VARIABLES;
                q.status = status;
                q.dignity=dignity;
                q.ego=ego;
                if (copy_to_user((query_arg_t *)arg, &q, sizeof(query_arg_t))
                {
                                return –EACCES;
                }
                break;
                case QUERY_CLR_VARIABLES:
                                status=0;
                                dignity=0;
                                ego=0;
                                break;
                default:
                                return –EINVAL;
     }
    return 0;
}

                And finally, the corresponding invocation functions from the application query_app.c would be as follows:
#include <stdio.h>
#include <sys/ioctl.h>
#include “query_ioctl.h”

void get_vars(int fd)
{
                query_arg_t q;
                if (ioctl(fd, QUERY_GET_VARIABLES, &q) == -1)
                {
                                perror("query_apps ioctl get");
`               }
                else
                {
                                printf("Status : %d\n", q.status):
                                printf("Dignity: %d\n", q.dignity);
                                printf("Ego       : %d\n", q.ego);
                }
}
void clr_vars(int fd)
{
                if(ioctl(fd, QUERY_CLR_VARIABLES) == -1)
                {
                                perror("query_apps ioctl clr");
                }
}

                The complete code of the above three files is available at http://linuxforu.com/article_source_code/aug11/ldd_code.tar.bz2, where the required file and other instructions also available.

Defining the ioctl() commands

1. The direction of command operation - read, write, both or none--filled by the corresponding macro (_IOR, _IOW, _IOWR, _IO).
2. The size of the command argument -- computed using sizeof() with the command argument's type--the third argument to these macros.
3. The 8-bit magic number--to render the commands unique enough--typically an ASCII character the first argument to these macros)
4. The original command umber--the actual command number (1,2,3,...), defined as per our requirement- the second argument to these macros.
      More detail regarding the same can be finding at <asm-generic/ioctl.h> for implementation.