Sunday, September 27, 2009

TALKING TO HARDWARE in C language.

inportb
Syntax
#include
unsigned char inportb(unsigned short _port);
Description
Read a single 8-bit I/O port.
This function is provided as an inline assembler macro, and will be optimized down to a single opcode when you optimize your program.
Return Value
The value returned through the port.
Portability
ANSI/ISO C No
POSIX No
*****************************************
Inportl
Syntax
#include
unsigned long inportl(unsigned short _port);
Description
This function reads a single 32-bit I/O port.
This function is provided as an inline assembler macro, and will be optimized down to a single opcode when you optimize your program.
Return Value
The value returned from the port.
Portability
ANSI/ISO C No
POSIX No
************************************************************
inportsb
Syntax
#include
void inportsb(unsigned short _port, unsigned char *_buf, unsigned _len);
Description
Reads the 8-bit _port _len times, and stores the bytes in buf.
Portability
ANSI/ISO C No
POSIX No
*************************************************************
inportsl
Syntax
#include
void inportsl(unsigned short _port, unsigned long *_buf, unsigned _len);
Description
Reads the 32-bit _port _len times, and stores the bytes in buf.
Portability
ANSI/ISO C No
POSIX No
*************************************************************
inportsw
Syntax
#include
void inportsw(unsigned short _port,
unsigned short *_buf, unsigned _len);
Description

Reads the 16-bit _port _len times, and stores the bytes in buf.
Portability
ANSI/ISO C No
POSIX No
**********************************************
inportw
Syntax
#include
unsigned short inportw(unsigned short _port);
Description
Read a single 16-bit I/O port.
This function is provided as an inline assembler macro, and will be optimized down to a single opcode when you optimize your program.
Return Value
The value returned through the port.
Portability
ANSI/ISO C No
POSIX No
**************************************************
inpw
Syntax

#include
unsigned short inpw(unsigned short _port);
Description
Calls inportw. Provided only for compatibility.
Portability
ANSI/ISO C No
POSIX No

*******************************************
Similarily with outport() also
All the above function are same for sendting data .. except change the in prefix to out

Socket Program in C

hey guys ! socket programing in C language..

you can chat with your friend .using this program,, try it ..


. TCP
* TCP server : simple TCP server that prints received messages.
source : tcpServer.c
usage : ./tcpServer
* TCP client : simple TCP client that sends data to server.
source : tcpClient.c
usage : ./tcpClient server data1 ... dataN

/*********************** tcpserver.c ***********************/
#include
#include
#include
#include
#include
#include
#include /* close */

#define SUCCESS 0
#define ERROR 1
#define END_LINE 0x0
#define SERVER_PORT 1500
#define MAX_MSG 100
/* function readline */
int read_line();
int main (int argc, char *argv[]) {
int sd, newSd, cliLen;
struct sockaddr_in cliAddr, servAddr;
char line[MAX_MSG];

/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd<0) {
perror("cannot open socket ");
return ERROR;
}
/* bind server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(SERVER_PORT);
if(bind(sd, (struct sockaddr *) &servAddr, sizeof(servAddr))<0) {
perror("cannot bind port ");
return ERROR;
}
listen(sd,5);
while(1) {
printf("%s: waiting for data on port TCP %u\n",argv[0],SERVER_PORT);
cliLen = sizeof(cliAddr);
newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen);
if(newSd<0) {
perror("cannot accept connection ");
return ERROR;
}
/* init line */
memset(line,0x0,MAX_MSG);
/* receive segments */
while(read_line(newSd,line)!=ERROR) {
printf("%s: received from %s:TCP%d : %s\n", argv[0],
inet_ntoa(cliAddr.sin_addr),
ntohs(cliAddr.sin_port), line);
/* init line */
memset(line,0x0,MAX_MSG);
} /* while(read_line) */
} /* while (1) */
}

/* WARNING WARNING WARNING WARNING WARNING WARNING WARNING */
/* this function is experimental.. I don't know yet if it works */
/* correctly or not. Use Steven's readline() function to have */
/* something robust. */
/* WARNING WARNING WARNING WARNING WARNING WARNING WARNING */
/* rcv_line is my function readline(). Data is read from the socket
when */
/* needed, but not byte after bytes. All the received data is read.
*/
/* This means only one call to recv(), instead of one call for
*/
/* each received byte.
*/
/* You can set END_CHAR to whatever means endofline for you. (0x0A is
\n)*/
/* read_lin returns the number of bytes returned in line_to_return
*/
int read_line(int newSd, char *line_to_return) {
static int rcv_ptr=0;
static char rcv_msg[MAX_MSG];
static int n;
int offset;
offset=0;
while(1) {
if(rcv_ptr==0) {
/* read data from socket */
memset(rcv_msg,0x0,MAX_MSG); /* init buffer */
n = recv(newSd, rcv_msg, MAX_MSG, 0); /* wait for data */
if (n<0) {
perror(" cannot receive data ");
return ERROR;
} else if (n==0) {
printf(" connection closed by client\n");
close(newSd);
return ERROR;
}
}
/* if new data read on socket */
/* OR */
/* if another line is still in buffer */
/* copy line into 'line_to_return' */
while(*(rcv_msg+rcv_ptr)!=END_LINE && rcv_ptrmemcpy(line_to_return+offset,rcv_msg+rcv_ptr,1);
offset++;
rcv_ptr++;
}
/* end of line + end of buffer => return line */
if(rcv_ptr==n-1) {
/* set last byte to END_LINE */
*(line_to_return+offset)=END_LINE;
rcv_ptr=0;
return ++offset;
}
/* end of line but still some data in buffer => return line */
if(rcv_ptr /* set last byte to END_LINE */
*(line_to_return+offset)=END_LINE;
rcv_ptr++;
return ++offset;
}
/* end of buffer but line is not ended => */
/* wait for more data to arrive on socket */
if(rcv_ptr == n) {
rcv_ptr = 0;
}
} /* while */
}

/*********************** tcpclient.c ***********************/

/* tcpClient.c */
#include
#include
#include
#include
#include
#include
#include /* close */
#define SERVER_PORT 1500
#define MAX_MSG 100
int main (int argc, char *argv[]) {
int sd, rc, i;
struct sockaddr_in localAddr, servAddr;
struct hostent *h;
if(argc < 3) {
printf("usage: %s ... \n",argv[0]);
exit(1);
}
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("%s: unknown host '%s'\n",argv[0],argv[1]);
exit(1);
}
servAddr.sin_family = h->h_addrtype;
memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0],
h->h_length);
servAddr.sin_port = htons(SERVER_PORT);
/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd<0) {
perror("cannot open socket ");
exit(1);
}
/* bind any port number */
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &localAddr, sizeof(localAddr));
if(rc<0) {
printf("%s: cannot bind port TCP %u\n",argv[0],SERVER_PORT);
perror("error ");
exit(1);
}
/* connect to server */
rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
if(rc<0) {
perror("cannot connect ");
exit(1);
}
for(i=2;i greater than argc;i++) {
rc = send(sd, argv[i], strlen(argv[i]) + 1, 0);
if(rc<0) {
perror("cannot send data ");
close(sd);
exit(1);
}
printf("%s: data%u sent (%s)\n",argv[0],i-1,argv[i]);
}
return

}

Friday, April 3, 2009

Some STUFF which helps U (SORTING TECHNIQUES)


insertion sort:-


One of the simplest sorting algorithms is the insertion sort. The code for the algorithm is as follows:

for(i = 1; i <>
Inserted = false; //boolean variable
j = i;
while((j >= 1) && (Inserted == false){
if(List[j] <>
swap(List[j], List[j-1]);
else
Inserted=true;
j--;
}
}


This algorithm works by first considering the first element of the list (element 0) to be correctly placed. It proceeds to the next element (element 1) and compares its value with. If the magnitude is smaller, it swaps it with element 0. Now, elements 0 and 1 are sorted, but only with respect to each other. Element 2 is now considered, and is moved to its correct position with respect to elements 0 and 1, i.e., it may stay where it currently is, or it may be placed between what are now elements 0 and 1, or it may be placed before element 0. To do this, elements 2 and 1 may be swapped, resulting in the placement of element 2 between what is currently element 0 and element 1, and then another swap between what are now elements 0 and 1 may be done to place the element before what is now element 0. This continues over and over again, considering the elements from element 3 through the last element of the list. Each element is placed in its proper position in the part of the list already consider to be sorted. Each element under consideration is swapped with its immediately preceeding neighbour as it moves towards the front of the list. The moment the swapping stops, the element's immediately preceding neighbor has lesser magnitude, and so the current element may be considered to be properly placed.

Complexity:

In this method there are N-1 insert operations. The j-th insert operation inserts a new element into a sorted array of j elements and hence takes at most j comparisions. Thus the total number of comparisions are:

1 + 2 + 3 + ... + (N-1) = N*(N-1)/2 = O(N^2)


INSERTION SORT II

iNSERTION SORT (A)
for j <-- 2 to length[A]
do key<--A[j]
//Insert A[j] into the sorted sequence A[1 . . . .j-1]
i <-- j - 1 while i > 0 and A[i] > key
do A[i + 1] <-- A[i]
i <-- i -1 A[i + 1] <-- key

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\


COUNTING SORT


Counting sort is a linear time sorting algorithm used to sort items when they belong to a fixed and finite set. Integers which lie in a fixed interval, say k1 to k2, are examples of such items.

The algorithm proceeds by defining an ordering relation between the items from which the set to be sorted is derived (for a set of integers, this relation is trivial).Let the set to be sorted be called A. Then, an auxiliary array with size equal to the number of items in the superset is defined, say B. For each element in A, say e, the algorithm stores the number of items in A smaller than or equal to e in B(e). If the sorted set is to be stored in an array C, then for each e in A, taken in reverse order, C[B[e]] = e. After each such step, the value of B(e) is decremented.


The algorithm makes two passes over A and one pass over B. If size of the range k is smaller than size of input n, then time complexity=O(n). Also, note that it is a stable algorithm, meaning that ties are resolved by reporting those elements first which occur first.

This visual demonstration takes 8 randomly generated single digit numbers as input and sorts them. The range of the inputs are from 0 to 9.

COUNTING SORT(A,B,k)

1 for i = 1 to k

2 do c[i] = 0

3 for j = 1 to length[A]

4 do C[A[j]] = C[A[j]] + 1

5 >C[i] now contains the number of elements equal to i

6 for i = 2 to k

7 do C[i] = C[i] + C[i-1]

8 >C[i] now contains the number of elements less than or equal to i

9 for j = length[A] downto 1

10 do B[C[A[j]]] = A[j]

11 C[A[j]] = C[A[J]] - 1

//////////////////////////////////////////////////////////////////////////////////////////////////

HEAP SORT

The heapsort algorithm uses the data structure called the heap. A heap is defined as a complete binary tree in which each node has a value greater than both its children (if any). Each node in the heap corresponds to an element of the array, with the root node corresponding to the element with index 0 in the array. Considering a node corresponding to index i, then its left child has index (2*i + 1) and its right child has index (2*i + 2). If any or both of these elements do not exist in the array, then the corresponding child node does not exist either. Note that in a heap the largest element is located at the root node. The code for the algorithm is:

Heapify(A, i){
l <- left(i)
r <- right(i)
if l <= heapsize[A] and A[l] > A[i]
then largest <- l
else largest <- i
if r <= heapsize[A] and A[r] > A[largest]
then largest <- r
if largest != i
then swap A[i] <-> A[largest]
Heapify(A, largest)
}

Buildheap(A){
heapsize[A] <- length[A]
for i <- |length[A]/2| downto 1
do Heapify(A, i)
}

Heapsort(A){
Buildheap(A)
for i <- length[A] downto 2
do swap A[1] <-> A[i]
heapsize[A] <- heapsize[A] - 1
Heapify(A, 1)
}

Heap Sort operates by first converting the initial array into a heap. The HeapSort algorithm uses a process called Heapify to accomplish its job. The Heapify algorithm, as shown above, receives a binary tree as input and converts it to a heap. The root is then compared with its two immediate children, and the larger child is swapped with it. This may result in one of the left or right subtrees losing their heap property. Consequently, the Heapify algorithm is recursively applied to the appropriate subtree rooted at the the node whose value was just swapped with the root and the process continues until either a leaf node is reached, or it is determined that the heap property is satisfied in the subtree.

The entire HeapSort method consists of two major steps:

STEP 1: Construct the initial heap using adjust (N/2) times on all non-leaf nodes.
STEP 2: Sort by swapping and adjusting the heap (N-1) times.

In step 2, since the largest element of the heap is always at the root, after the initial heap is constructed, the root value is swapped with the lowest, rightmost element. This node corresponds to the last element of the array and so after the swapping the righmost element of the array has the largest value, which is what we want it to have. Consequently, the rightmost element is correctly place, and so the corresponding node becomes a light gray in the tree display depicting the heap. Also, the elements (nodes) chosen for swapping at this point of the algorithm are shown as yellow nodes.

Thereafter, since the value of the lowest, rightmost node has moved up to the root, the heap property of the rest of the heap (minus the gray nodes) has been disturbed. Consequently, now the Heapify process is applied to the rest of the heap (treating the light gray nodes as though they were no longer a part of the heap). Once the rest of the heap is again converted to a proper heap, the swapping process as described in the previous paragraph, followed by the Heapify process is applied again. This continues until the root node of the heap turns light gray - i.e., the root has its correct value. Then, the array is sorted.




At each step of the Heapify algorithm, a node is compared to its children and one of them is chosen as the next root. One level of the tree is dropped at each step of this process. Since the heap is a complete binary tree, there are atmost log(N) levels. Thus, the worst case time complexity of Heapify is O(log(N)). In the Heapsort algorithm, Heapify is used (N/2) times to construct the initial heap and (N-1) times to sort. Thus the Heapsort algorithm has a worst case time complexity of O(N*log(N)).

******************************************************************************

POSTMAN SORT


Postman Sort is probably the newest linear order sorting algorithm for fixed domain sets in use today. It's developers claim that it is also the fastest such algorithm.

The algorithm works by sorting the numbers from their most significant digit to their least significant digit. Significant gain in speed is achieved by sorting the numbers on more than one digit at a time (the actual number is decided based on the size of the computer's memory). The process is also considerably speeded up by using some knowledge of the range in which the numbers lie, for example the fact that digits of octal numbers lie in the range 0 to 7.

For this visual demonstration we have sorted randomly input 9 digit binary numbers, using 3 digits at a time (The use of binary numbers enhances the clarity of the visual representation considerably).

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

RADIX SORT


Radix sort is one of the linear sorting algorithms for integers. It functions by sorting the input numbers on each digit, for each of the digits in the numbers. However, the process adopted by this sort method is somewhat counterintuitive, in the sense that the numbers are sorted on the least-significant digit first, followed by the second-least significant digit and so on till the most significant digit.

To appreciate Radix Sort, consider the following analogy: Suppose that we wish to sort a deck of 52 playing cards (the different suits can be given suitable values, for example 1 for Diamonds, 2 for Clubs, 3 for Hearts and 4 for Spades). The 'natural' thing to do would be to first sort the cards according to suits, then sort each of the four seperate piles, and finally combine the four in order. This approach, however, has an inherent disadvantage. When each of the piles is being sorted, the other piles have to be kept aside and kept track of. If, instead, we follow the 'counterintuitive' aproach of first sorting the cards by value, this problem is eliminated. After the first step, the four seperate piles are combined in order and then sorted by suit. If a stable sorting algorithm (i.e. one which resolves a tie by keeping the number obtained first in the input as the first in the output) it can be easily seen that correct final results are obtained.

As has been mentioned, the sorting of numbers proceeds by sorting the least significant to most significant digit. For sorting each of these digit groups, a stable sorting algorithm is needed. Also, the elements in this group to be sorted are in the fixed range of 0 to 9. Both of these characteristics point towards the use of Counting Sort as the sorting algorithm of choice for sorting on each digit (If you haven't read the description on Counting Sort already, please do so now).

The time complexity of the algorithm is as follows: Suppose that the n input numbers have maximum k digits. Then the Counting Sort procedure is called a total of k times. Counting Sort is a linear, or O(n) algorithm. So the entire Radix Sort procedure takes O(kn) time. If the numbers are of finite size, the algorithm runs in O(n) asymptotic time.

A graphical representation of the entire procedure has been provided in the attached applet. This program takes 8 randomly generated 3 digit integers as input and sorts them using Radix Sort.

RADIX-SORT(A,d)

1 for i - 1 to d

2 do use a stable sort to sort Array A on digit i


xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx




The mergesort algorithm closely follows the divide-and-conquer paradigm. Generally, Merge Sort is considered to be one of the best internal sorting methods. If the data is too large to be accommodated all at once in the memory then one has to use external sorting methods. In external sorting methods small blocks of data are loaded into the memory, sorted using an internal sorting method and written out to a tape or disk. Sorted parts are then merged using variations of the merging algorithm discussed below:

Mergesort(A,p,r){
if p <>
then q <- |(p+ r)/2|
Mergesort(A,p,q)
Mergesort(A,q+1,r)
Merge(A,p,q,r)
}

To sort the entire sequence A, Mergesort(A,1,length[A]) is called where length[A]=N.

Mergesort works by splitting the list into two halves and then sorting each half recursively. Mergesort may be considered to be a tree based algorithm and over here it is executed in a depth first manner. For the above list the algorithm starts by handling the merging of elements as follows (the trend in which the sublists are being considered):

1. First, elements 1 and 2 are handled.
2. Then, elements from 0 through 2 are handled (note the black items indicating the border elements).
3. Then, elements 3 and 4 are handled. After this, elements 5 and 6.
4. Then, elements 3 through 6 are handled.

Subsequently, elements 0 through 6 are handled and so on until elements 0 to 14 are handled.

The Merge algorithm takes two sorted lists and merges them to give a sorted list. It assumes the existence of a temporary merge space whose current contents are shown on the upper canvas of the above applet. Mereg takes the the smaller of the first elements of the two lists and places it into the merge space. When either input list is exhausted, the remainder of the other list is copied to the merge space. The sorted sublist is then copied back from the merge space into the appropriate indices.


Merge Sort algorithm uses the process of merging two sorted lists recursively to accomplish the sorting of an unsorted list. Firstly, two sorted lists of length M and N respectively can be merged in O(M+N) time. If the lists have the same size N then the time will be O(2*N) or O(N).
First, each individual element of the list is considered as a 1-element sorted list. The merge algorithm is then used N/2 times to merge pairs of elements into sorted lists of length 2. This will produce N/2 sorted lists each of length 2. It takes N/2 comparisons to accomplish this. Pairs of 2-element lists are then merged to produce N/4 sorted lists each of length 4. In this case there are N/4 merge operations each taking at most 4 comparisons. This process continues until we have two sorted lists of size N/2 and we merge them in O(N) time. There are log(N) levels of merging. Hence, Merge Sort has a worst-case complexity of O(N*log(N)).

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

HEAPSORT ii


The running time of heapsort is O(N*lgN) i.e. it achieves the lower bound for computational based sorting.

HEAP
The heap data structure is an array object which can be easily visualized as a complete binary tree.There is a one to one correspondence between elements of the array and nodes of the tree.The tree is completely filled on all levels except possibly the lowest,which is filled from the left upto a point.All nodes of heap also satisfy the relation that the key value at each node is at least as large as the value at its children.

Step I: The user inputs the size of the heap(within a specified limit).The program generates a corresponding binary tree with nodes having randomly generated key Values.

Step II: Build Heap Operation:Let n be the number of nodes in the tree and i be the key of a tree.For this,the program uses operation Heapify.when Heapify is called both the left and right subtree of the i are Heaps.The function of Heapify is to let i settle down to a position(by swapping itself with the larger of its children,whenever the heap property is not satisfied)till the heap property is satisfied in the tree which was rooted at (i).This operation calls

Step III: Remove maximum element:The program removes the largest element of the heap(the root) by swapping it with the last element.

Step IV: The program executes Heapify(new root) so that the resulting tree satisfies the heap property.
Step V: Goto step III till heap is empty





Quicksort is based on the divide and conquer approach and inspite of its slow worst case running time, it is often the best practical choice for sorting because it is remarkably efficient on the average. The following code describes the algorithm:

QuickSort(A, p, r){
if p <>
then q <- Partition(A, p, r)
QuickSort(A, p, q)
QuickSort(A, q+1, r)
}

To sort an entire array A, the initial call is QuickSort(A, 1, length[A]).

Partition(A, p, r){
x <- A[p]
i <- p - 1
j <- r + 1
while TRUE
do repeat j <- j - 1
until A[j] <= x
repeat i <- i + 1
until A[i] >= x
if i <>
then exchange A[i] <-> A[j]
else return j
}







The algorithm starts by first performing a scan of the entire list, as indicated by the two black items at the two ends of the list. It attempts then to partition the list. The manner in which this partitioning is done is: First, the pivot element is considered to be the first element of the (sub)list being scanned, i.e., element 0. The high-pointer is shown in green and the low-pointer in blue. Scanning of the (sub)list consists of decrementing the high-pointer and incrementing the low-pointer until A[low-pointer]>= A[pivot] >= A[high-pointer]. As the scan of the (sub)list proceeds, the magnitudes of the list elements are compared with the magnitude of the pivot. First the high-pointer is decremented till it meets an element that is less than or equal to the pivot. Then the low-pointer is incremented till it meets an element greater than equal to the pivot. If the low-pointer is less than the high-pointer, then the elements pointed to by these are swapped else the element pointed by the high-pointer becomes the pivot. Conceptually, the partitioning procedure performs a simple function: it puts elemnts smaller than the pivot into the bottom region of the array and elements larger than the pivot into the top region. Now, the same partitioning approach can be recursively applied to the smaller sublist and also to the larger sublist obtained as a result of the partitioning. Repeated applications of this approach to all sublists generated results in a sorted list.



Quicksort works by partitioning the list into two parts. The first partitioning of the N elements in list positions 0 to N-1, compares and swaps them to produce a pivotal index j such that the elements in positions 0 to j-1 are less than or equal to the pivot which is now in the jth position and those elements in positions j+1 to N-1 are greater. This is accomplished in O(N) time.
The first partition produces two sublists such that sorting of each of them results in the sorting of the original list. The partitioning technique is applied recursively to each half until the halves reduce to single-element or empty lists.
Assuming that the list breaks into two halves of equal size, then we have two lists of size N/2 to sort. Each of these has to be partitioned which takes (N/2) + (N/2) = N comparisions. Continuing the same assumption, there will be atmost log(N) splits. This results in the best case time estimate of O(N*log(N)) for quicksort.
In the worst case, the partitioning routine produces one region with (N-1) elements and one with only one element (this happens when the list to be sorted is already sorted). This gives a worst case time of O(N^2). However, quicksort takes O(N*log(N)) in the average case.2

MERGE SORT

The mergesort algorithm is based on the classical divide-and-conquer paradigm. It operates as follows:

DIVIDE: Partition the n-element sequence to be sorted into two subsequences of n/2 elements each.

CONQUER: Sort the two subsequences recursively using the mergesort.

COMBINE: Merge the two sorted sorted subsequences of size n/2 each to produce the sorted sequence consisting of n elements.

Note that recursion "bottoms out" when the sequence to be sorted is of unit length. Since every sequence of length 1 is in sorted order, no further recursive call is necessary. The key operation of the mergesort algorithm is the merging of the two sorted sequencesin the "combine step". To perform the merging, we use an auxilliary procedure Merge(A,p,q,r), where A is an array and p,q and r are indices numbering elements of the array such that dure assumes that the subarrays A[p..q] and A[q+1...r] are in sorted order.It merges them to form a single sorted subarray that replaces the current subarray A[p..r]. Thus finally,we obtain the sorted array A[1..n], which is the solution.


MERGE SORT (A,p,r)
1 if p <>then q<-- [ (p + r) / 2 ] 3 MERGE SORT(A,p,q)
4 MERGER SORT(A,q + 1,r)
5 MERGE(A,p,q,r)


QUICK SORT

Quick sort,is based on the divide-and-conquer paradigm.It is a sorting algorithm with worst case running time O(n^2) on an input array of n numbers.In spite of this slow worst case running time,quicksort is often the best practical choice for sorting because it is remarkably efficient on the average : its expected running time is O(nlgn) and the constants hidden in the O-notation are quite small.Here is the three-step divide-and-conquer process for sorting a typical array A[p . . . r]

DIVIDE:The array >A is partitioned (rearranged) into two nonempty subarrays A[p . . q] and A[q+1 . . r].The index q is computed as a part of this partitioning procedure.

CONQUER:The two subarrays A[p . . q] and A[q+1 . . r] are sorted by recursive calls to quicksort.

COMBINE:Since the subarrays are sorted in place, no work is needed to combine them : the entire array A is now sorted.


QUICK SORT (A,p,r)
1 if p <>then q<-- PARTITION(A,p,r)
3 QUICK SORT(A,p,q)
4 QUICK SORT(A,q + 1,r)




Thursday, March 19, 2009

POST Power On Self Test .. Know your computer...

What happens when your computer starts up and when it shuts down
Starting Up

What happens when a computer starts? - POST - Power On Self Test
Although there are differences in how each computer actually starts, they all share these basic steps. This example is particularly directed towards Dos and Windows (except where noted).
• The computer performs a test on itself to make sure all components are available and ready. One important part of the first steps is that the registers (the place where data and instructors go in the CPU to be processed) are cleared of any old code. This is the start of the Power-On Self Test or POST test.
• The CPU then gets a memory address from the ROM which where to find the ROM BIOS in order to continue the check.
• The CPU now sends signals on its system bus, the main circuit on the mother board to which all components are attached.
• The clock is checked by the CPU. All computer functions are regulated by this clock, which sends an impulse at a regular interval. It is very much similar to the beating of a bass drum to mark time in music.
• POST tests the memory chips on the video adapter and loads information from the video adapter’s own BIOS into the system BIOS. Sometimes the BIOS codes from slower CMOS are also loaded into RAM. Newer PCs have additional equipment which also have their own BIOS on their own cards. These items, called plug and play also get loaded into the system BIOS.
• The CPU now checks to see if a keyboard is attached, if it is working correctly and if any keys are pressed. Many operating systems permit the user to interrupt the POST test to change the computer’s initial or default behaviors (or environmental variables).
• POST now checks the paths on the bus to the floppy and harddrives (and other devices) to see what storage and peripheral devices are available.
• Once all the components contribute information to the system BIOS, and all other checks have been performed, if the test indicates a problem, such as a corrupted FAT table, the test will inform you and usually offer a change to fix the problem via a setup screen. If there are no problems, the operating system will display some form of greeting: on a Windows machine, you see a large Microsoft logo. On a Macintosh, you’ll read "Welcome to Macintosh." Command-line systems, such as Unix, may show nothing but a prompt.

To start the computer in safe mode
You should print these instructions before continuing. They will not be available after you shut your computer down in step 2.
1. Click Start, click Shut Down, and then, in the drop-down list, click Shut down.
2. In the Shut Down Windows dialog box, click Restart, and then click OK.
3. When you see the message Please select the operating system to start, press F8.
4. Use the arrow keys to highlight the appropriate safe mode option, and then press ENTER.
5. If you have a dual-boot or multiple-boot system, choose the installation that you need to access using the arrow keys, and then press ENTER.
Notes
In safe mode, you have access to only basic files and drivers (mouse, monitor, keyboard, mass storage, base video, default system services, and no network connections). You can choose the Safe Mode with Networking option, which loads all of the above files and drivers and the essential services and drivers to start networking, or you can choose the Safe Mode with Command Prompt option, which is exactly the same as safe mode except that a command prompt is started instead of the graphical user interface. You can also choose Last Known Good Configuration, which starts your computer using the registry information that was saved at the last shutdown.
Safe mode helps you diagnose problems. If a symptom does not reappear when you start in safe mode, you can eliminate the default settings and minimum device drivers as possible causes. If a newly added device or a changed driver is causing problems, you can use safe mode to remove the device or reverse the change.
There are circumstances where safe mode will not be able to help you, such as when Windows system files that are required to start the system are corrupted or damaged. In this case, the Recovery Console may help you.
NUM LOCK must be off before the arrow keys on the numeric keypad will function.

Shutting Down
What happens when you shut down
Shut Down allows you to gracefully shut down Windows by first saving any open files or reminding you to do so, and then deleting any temporary files that have been in use and are no longer needed. The Shut Down option gives you the option to restart your computer, the equivalent of rebooting, either back into Windows or to DOS. You can protect yourself from losing unsaved information by always using Shut Down when leaving Windows and turning off your computer.
To turn off the computer
Click Start, click Shut Down, and then, in the drop-down list, click Shut down.
This action shuts down Windows so that you can safely turn off the computer power. Many computers turn the power off automatically.
To restart your computer
Click Start, and then click Shut Down.
In the What do you want the computer to do drop-down list, click Restart.
As a last resort
Hit Ctrl-Alt-Delete. The Task Manager should come up. Try closing down any open/stalled programs by hitting End Task (and End Task again if the window comes up), and then Shut Down again. If that doesn't work, hit Ctrl-Alt-Delete several times until the computer reboots. As a final resort, hold the power button on the computer in until the computer shuts off.

Know Your Computer..

Serial Communication Porgramming In C..

RS232 is the most known serial port used in transmitting the data in communication and interface. Even though serial port is harder to program than the parallel port, this is the most effective method in which the data transmission requires less wires that yields to the less cost. The RS232 is the communication line which enables the data transmission by only using three wire links. The three links provides ‘transmit’, ‘receive’ and common ground...


To download the code ..........http://electrosofts.com/serial/


You find a link for sample code.. download it

Computer Register..Play with it....

In computer architecture, a processor register is a small amount of storage available on the CPU whose contents can be accessed more quickly than storage available elsewhere. Most, but not all, modern computer architectures operate on the principle of moving data from main memory into registers, operating on them, then moving the result back into main memory—a so-called load-store architecture. A common property of computer programs is locality of reference: the same values are often accessed repeatedly; and holding these frequently used values in registers improves program execution performance.

Processor registers are at the top of the memory hierarchy, and provide the fastest way for a CPU to access data. The term is often used to refer only to the group of registers that are directly encoded as part of an instruction, as defined by the instruction set. More properly, these are called the "architectural registers". For instance, the x86 instruction set defines a set of eight 32-bit registers, but a CPU that implements the x86 instruction set will often contain many more registers than just these eight.

Allocating frequently used variables to registers can be critical to a program's performance. This action, namely register allocation is performed by a compiler in the code generation phase.




Categories of registers

Registers are normally measured by the number of bits they can hold, for example, an "8-bit register" or a "32-bit register". Registers are now usually implemented as a register file, but they have also been implemented using individual flip-flops, high speed core memory, thin film memory, and other ways in various machines.

A processor often contains several kinds of registers, that can be classified according to their content or instructions that operate on them:

* User-accessible Registers - The most common division of user-accessible registers is into data registers and address registers.
* Data registers are used to hold numeric values such as integer and floating-point values. In some older and low end CPUs, a special data register, known as the accumulator, is used implicitly for many operations.
* Address registers hold addresses and are used by instructions that indirectly access memory.
o Some processors contain registers that may only be used to hold an address or only to hold numeric values (in some cases used as an index register whose value is added as an offset from some address); others allow registers hold either kind of quantity. A wide variety of possible addressing modes, used to specify the effective address of an operand, exist.

To Know more .....follow the link Processor and Regiters

Thursday, March 12, 2009

Web programming at your finger tips ......

Its a great site for learning web programming........
visit the site .....Become Web Programmer within no time...