| Bubble Sort | Insertion Sort | Selection Sort | Shell Sort | Merge Sort | Quick Sort | Heap Sort | Binary Search Algorithm |
Merge Sort
Merge Sort
Algorithm:
Properties:
Merge Sort Visualization :
Here's a Java Applet Visualization which might help you get a clearer idea of what exactly happens in merge-sort.
Merge Sort - C Program Source Code
#include<stdio.h>
/*This is called Forward declaration of function */
void Merge(int * , int , int , int );
/* Logic: This is divide and conquer algorithm. This works as follows.
(1) Divide the input which we have to sort into two parts in the middle. Call it the left part
and right part.
Example: Say the input is -10 32 45 -78 91 1 0 -16 then the left part will be
-10 32 45 -78 and the right part will be 91 1 0 6.
(2) Sort Each of them seperately. Note that here sort does not mean to sort it using some other
method. We already wrote fucntion to sort it. Use the same.
(3) Then merge the two sorted parts.
*/
/*This function Sorts the array in the range [left,right].That is from index left to index right inclusive
*/
void MergeSort(int *array, int left, int right)
{
int mid = (left+right)/2;
/* We have to sort only when left<right because when left=right it is anyhow sorted*/
if(left<right)
{
/* Sort the left part */
MergeSort(array,left,mid);
/* Sort the right part */
MergeSort(array,mid+1,right);
/* Merge the two sorted parts */
Merge(array,left,mid,right);
}
}
/* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
*/
void Merge(int *array, int left, int mid, int right)
{
/*We need a Temporary array to store the new sorted part*/
int tempArray[right-left+1];
int pos=0,lpos = left,rpos = mid + 1;
while(lpos <= mid && rpos <= right)
{
if(array[lpos] < array[rpos])
{
tempArray[pos++] = array[lpos++];
}
else
{
tempArray[pos++] = array[rpos++];
}
}
while(lpos <= mid) tempArray[pos++] = array[lpos++];
while(rpos <= right)tempArray[pos++] = array[rpos++];
int iter;
/* Copy back the sorted array to the original array */
for(iter = 0;iter < pos; iter++)
{
array[iter+left] = tempArray[iter];
}
return;
}
int main()
{
int number_of_elements;
scanf("%d",&number_of_elements);
int array[number_of_elements];
int iter;
for(iter = 0;iter < number_of_elements;iter++)
{
scanf("%d",&array[iter]);
}
/* Calling this functions sorts the array */
MergeSort(array,0,number_of_elements-1);
for(iter = 0;iter < number_of_elements;iter++)
{
printf("%d ",array[iter]);
}
printf("\n");
return 0;
}
Merge Sort - Java Program Source Code
Post to LiveJournalimport java.io.*; /* Logic: This is divide and conquer algorithm. This works as follows. (1) Divide the input which we have to sort into two parts in the middle. Call it the left part and right part. Example: Say the input is -10 32 45 -78 91 1 0 -16 then the left part will be -10 32 45 -78 and the right part will be 91 1 0 6. (2) Sort Each of them seperately. Note that here sort does not mean to sort it using some other method. We already wrote fucntion to sort it. Use the same. (3) Then merge the two sorted parts. */ /*This function Sorts the array in the range [left,right].That is from index left to index right inclusive */ class MeregeSort { void MergeSort(int array[], int left, int right) { int mid = (left+right)/2; /* We have to sort only when left<right because when left=right it is anyhow sorted*/ if(left<right) { /* Sort the left part */ MergeSort(array,left,mid); /* Sort the right part */ MergeSort(array,mid+1,right); /* Merge the two sorted parts */ Merge(array,left,mid,right); } } /* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right]. */ void Merge(int array[], int left, int mid, int right) { /*We need a Temporary array to store the new sorted part*/ int tempArray[]=new int[right-left+1]; int pos=0,lpos = left,rpos = mid + 1; while(lpos <= mid && rpos <= right) { if(array[lpos] < array[rpos]) { tempArray[pos++] = array[lpos++]; } else { tempArray[pos++] = array[rpos++]; } } while(lpos <= mid) tempArray[pos++] = array[lpos++]; while(rpos <= right)tempArray[pos++] = array[rpos++]; int iter; /* Copy back the sorted array to the original array */ for(iter = 0;iter < pos; iter++) { array[iter+left] = tempArray[iter]; } return; } int main()throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int number_of_elements; System.out.println("Enter the number of elements"); number_of_elements=Integer.parseInt(in.readLine()); int array[]=new int[number_of_elements]; int iter; System.out.println("Enter the elements one by one"); for(iter = 0;iter < number_of_elements;iter++) { array[iter]=Integer.parseInt(in.readLine()); } /* Calling this functions sorts the array */ MergeSort(array,0,number_of_elements-1); for(iter = 0;iter < number_of_elements;iter++) { System.out.print(array[iter]+"\t"); } System.out.print("\n"); return 0; } }
MCQ Quiz: Efficient Sorting Algorithms- Quick sort, Merge Sort, Heap Sort- Check how much you can score!
MCQ Quiz- More efficient sorting algorithms
One
of the most elementary sorting algorithms to implement - and also very
inefficient. Runs in quadratic time. A good starting point to understand
sorting in general, before moving on to more advanced techniques and
algorithms. A general idea of how the algorithm works and a the code for
a C program. |
Another quadratic time sorting algorithm - an example of dynamic programming. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs insertion sort. |
Another quadratic time sorting algorithm - an example of a greedy algorithm. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs selection sort. |
An inefficient but interesting algorithm, the complexity of which is not exactly known. |
An example of a Divide and Conquer algorithm. Works in O(n log n) time. The memory complexity for this is a bit of a disadvantage. |
In the average case, this works in O(n log n) time. No additional memory overhead - so this is better than merge sort in this regard. A partition element is selected, the array is restructured such that all elements greater or less than the partition are on opposite sides of the partition. These two parts of the array are then sorted recursively. |
Efficient sorting algorithm which runs in O(n log n) time. Uses the Heap data structure. |
Commonly used algorithm used to find the position of an element in a sorted array. Runs in O(log n) time. |
Merge Sort Visualization :
Here's a Java Applet Visualization which might help you get a clearer idea of what exactly happens in merge-sort.
Recommended books for learning Computer Science, learning high quality programming, and preparing for programming interviews:
| 1. A good knowledge of Data Structures, Algorithm Design and Analysis of Complexity
The books by Cormen or
Sedgewick (a standard part of the undergraduate curriculum) are
sufficient for this part of the preparation. Google specially, loves to
focus on algorithmic questions.
|
|
|
|
|
| 2. Standard and established sources of Programming Interview Questions A lot of interview questions are re-used and re-cycled by interviews again and again. Chances are, that question you're going to be asked, has been asked a hundred times during the last week, across a number of companies! Google, Facebook, Microsoft, Amazon- all of them frequently ask questions on the lines of those in these books. |
Cracking the Coding Interview: 150 Programming Questions and Solutions [Paperback] | |
|
|
| 3. Puzzles and Brainteasers (often asked, good to be prepared) Questions from Mount Fuji are specially popular with Microsoft recruiters. |
How would you move Mount Fuji? |
|
||
| 4. Good Software Engineering practices. Writing
clean and secure code, an awareness about Design Patterns and Object
Oriented Programming techniques. Some of these books are frequently
recommended by Microsoft recruiters. Take care of buffer overflows! Code Complete is a recommended book for Microsoft Interviews. |
|
|
|
|
| In case your primary language is C++, make sure you know its "ins-and-outs". You should know about destructors and constructors, virtual destructors, polymorphism, function overloading. Some of these books might help you revise C++. | |
|
|
|
| In case your primary language is C, make sure to be well versed with pointers, system calls and how they work. How does Malloc work, how does calloc work? All of these are questions which some interviewers could potentially ask, to test the depth of your knowledge and your understanding of the system "under the hood". | |
|
||
| Here's a great book for the Java lovers as well. It normally doesn't matter which programming language you know, but make sure to know about it in detail. |
|
Testing Zone For Programmers-
Try out our online Multiple-Choice-Question tests in Programming and Computer Science!
Arrays : Popular Sorting and Searching Algorithms |
| ||
| Selection Sort | Shell Sort | ||
| Heap Sort | Binary Search Algorithm | ||
Basic Data Structures and Operations on them | |||
| Single Linked List | Double Linked List | ||
| Tree Data Structures | |||
| Binary Search Trees | Heaps | Height Balanced Trees | |
| Graphs and Graph Algorithms | |||
| Depth First Search | Breadth First Search | Minimum Spanning Trees: Kruskal Algorithm | Minumum Spanning Trees: Prim's Algorithm |
| Dijkstra Algorithm for Shortest Paths | Floyd Warshall Algorithm for Shortest Paths | Bellman Ford Algorithm | |
| Popular Algorithms in Dynamic Programming | |||
| Dynamic Programming | Integer Knapsack problem | Matrix Chain Multiplication | Longest Common Subsequence |
| Greedy Algorithms | |||
| Elementary cases : Fractional Knapsack Problem, Task Scheduling | Data Compression using Huffman Trees |
Bubble Sort - One of the most elementary sorting algorithms to implement - and also very inefficient. Runs in quadratic time. A good starting point to understand sorting in general, before moving on to more advanced techniques and algorithms. A general idea of how the algorithm works and a the code for a C program. Insertion Sort - Another quadratic time sorting algorithm - an example of dynamic programming. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs insertion sort. Selection Sort - Another quadratic time sorting algorithm - an example of a greedy algorithm. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs selection sort. Shell Sort- An inefficient but interesting algorithm, the complexity of which is not exactly known. Merge Sort An example of a Divide and Conquer algorithm. Works in O(n log n) time. The memory complexity for this is a bit of a disadvantage. Quick Sort In the average case, this works in O(n log n) time. No additional memory overhead - so this is better than merge sort in this regard. A partition element is selected, the array is restructured such that all elements greater or less than the partition are on opposite sides of the partition. These two parts of the array are then sorted recursively. Heap Sort- Efficient sorting algorithm which runs in O(n log n) time. Uses the Heap data structure. Binary Search Algorithm- Commonly used algorithm used to find the position of an element in a sorted array. Runs in O(log n) time. |











