Skip to main content

Posts

Showing posts from December, 2014

Rotate array Elements

How to you a write a function to rotate elements of a an array by n places. Save last element of array in temp Copy a[i-1] to a[i] for all i from len-1 to 1.                for(i=len-1;i>0;i--)                  a[i] = a[i-1]; Copy temp to a[0] Repeat these 3 steps n number of times void rotoateElements(int arr[],int len,int nbits) { int i,j; for(j=0;j<nbits;j++) { int temp=a[len-1]; //Save last element for(i=len-1;i>0;i--) { a[i]=a[i-1];//shift each element by one place } a[0] = temp;//copy last element to 0th element } }

Sorting a linked list

How do we sort a linked list? Try this method - this is simple insertion sort method. Easily implementable in LL. 1) Create a new list called sorted list 2) Take one node from list, delete it. And add it to the sorted list 3) Take the next node - nodenew, traverse through sorted list till you find a node with key value greater than nodenew, and insert the nodenew before this node. Of course you have to delete nodenew from original list. 4) Continue this process until the original list is empty. The complexity - O(n 2 )  struct node { int n; struct node *next; }; typedef struct node *NODEPTR: NODEPTR sortList(NODEPTR head) { NODEPTR newList = NULL; while(head!=NULL) { NODEPTR temp = head; head = head->next; temp->next = NULL; newList = insertSorted(newList,temp); } printList(newList); return newList; } NODEPTR insertSorted(NODEPTR head,NODEPTR newnode) { NODEPTR temp, prevNode=head; if(head==NULL) r