0
The runtime complexity of the mergesort algorithm is O(n log n), where n is the number of elements in the input array.
1 answer
Empirically, heapsort and mergesort have similar performance in terms of speed, but the specific efficiency may vary depending on the data set and implementation.
1 answer
try making yourself..hope it will be useful ofr you!
1 answer
#include <stdio.h>
#include <stdlib.h>
#define MAXARRAY 10
void mergesort(int a[], int low, int high);
int main(void) {
int array[MAXARRAY];
int i = 0;
/* load some random values into the array */
for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;
/* array before mergesort */
printf("Before :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);
printf("\n");
mergesort(array, 0, MAXARRAY - 1);
/* array after mergesort */
printf("Mergesort :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);
printf("\n");
return 0;
}
void mergesort(int a[], int low, int high) {
int i = 0;
int length = high - low + 1;
int pivot = 0;
int merge1 = 0;
int merge2 = 0;
int working[length];
if(low == high)
return;
pivot = (low + high) / 2;
mergesort(a, low, pivot);
mergesort(a, pivot + 1, high);
for(i = 0; i < length; i++)
working[i] = a[low + i];
merge1 = 0;
merge2 = pivot - low + 1;
for(i = 0; i < length; i++) {
if(merge2 <= high - low)
if(merge1 <= pivot - low)
if(working[merge1] > working[merge2])
a[i + low] = working[merge2++];
else
a[i + low] = working[merge1++];
else
a[i + low] = working[merge2++];
else
a[i + low] = working[merge1++];
}
}
1 answer
Mergesort and heapsort are both comparison-based sorting algorithms. The key difference lies in their approach to sorting. Mergesort uses a divide-and-conquer strategy, splitting the array into smaller subarrays, sorting them, and then merging them back together. Heapsort, on the other hand, uses a binary heap data structure to maintain the heap property and sort the elements.
In terms of time complexity, both mergesort and heapsort have an average and worst-case time complexity of O(n log n). However, mergesort typically performs better in practice due to its stable time complexity.
In terms of space complexity, mergesort has a space complexity of O(n) due to the need for additional space to store the subarrays during the merge phase. Heapsort, on the other hand, has a space complexity of O(1) as it sorts the elements in place.
Overall, mergesort is often considered more efficient in terms of time complexity and stability, while heapsort is more space-efficient. The choice between the two algorithms depends on the specific requirements of the sorting task at hand.
1 answer
The built in array sorting algorithm (java.util.Arrays.sort) depends on the type of data being sorted. Primitive types are sorted with a modified implementation of quicksort. Objects are sorted with a modified implementation of mergesort.
1 answer
Heapsort and mergesort are both comparison-based sorting algorithms. The key differences between them are in their approach to sorting and their time and space complexity.
Heapsort uses a binary heap data structure to sort elements. It has a time complexity of O(n log n) in the worst-case scenario and a space complexity of O(1) since it sorts in place.
Mergesort, on the other hand, divides the array into two halves, sorts them recursively, and then merges them back together. It has a time complexity of O(n log n) in all cases and a space complexity of O(n) since it requires additional space for merging.
In terms of time complexity, both algorithms have the same efficiency. However, in terms of space complexity, heapsort is more efficient as it does not require additional space proportional to the input size.
1 answer
Merge sort (or mergesort) is an algorithm. Algorithms do not have running times since running times are determined by the algorithm's performance/complexity, the programming language used to implement the algorithm and the hardware the implementation is executed upon. When we speak of algorithm running times we are actually referring to the algorithm's performance/complexity, which is typically notated using Big O notation.
Mergesort has a worst, best and average case performance of O(n log n). The natural variant which exploits already-sorted runs has a best case performance of O(n). The worst case space complexity is O(n) auxiliary.
3 answers
Some popular sorting algorithms used in online platforms for organizing data efficiently include quicksort, mergesort, and heapsort. These algorithms are commonly used to arrange data in a specific order, making it easier to search and access information quickly.
1 answer
Merging data when sorting (which occurs with mergesort, quicksort, and others) is based on the idea that merging two sorted lists is faster than merging two unsorted lists. This makes sense - it will take less comparisons to merge {1 3 5} and {2 4 6} than {3 1 5} and {6 4 2}.
1 answer
Some examples of efficient algorithms used in data processing and analysis include sorting algorithms like quicksort and mergesort, searching algorithms like binary search, and machine learning algorithms like k-means clustering and decision trees. These algorithms help process and analyze large amounts of data quickly and accurately.
1 answer
To implement a merge sort algorithm for a doubly linked list in Java, you can follow these steps:
You can achieve this by creating a mergeSort() method that takes the doubly linked list as input and recursively divides and merges the list. Make sure to handle the merging process for doubly linked lists by adjusting the pointers accordingly.
Here is a basic outline of how you can implement this algorithm in Java:
java public class MergeSortDoublyLinkedList
public Node mergeSort(Node head)
if (head null head.next null)
return head;
Node middle getMiddle(head);
Node nextOfMiddle middle.next;
middle.next null;
Node left mergeSort(head);
Node right mergeSort(nextOfMiddle);
return merge(left, right);
private Node merge(Node left, Node right)
if (left null)
return right;
if (right null)
return left;
Node result null;
if (left.data right.data)
result left;
result.next merge(left.next, right);
result.next.prev result;
else
result right;
result.next merge(left, right.next);
result.next.prev result;
return result;
private Node getMiddle(Node head)
if (head null)
return head;
Node slow head;
Node fast head;
while (fast.next ! null fast.next.next ! null)
slow slow.next;
fast fast.next.next;
return slow;
class Node
int data;
Node prev;
Node next;
public Node(int data)
this.data data;
This code snippet provides a basic implementation of the merge sort algorithm for a doubly linked list in Java. You can further customize and optimize it based on your specific requirements.
1 answer
If there was a way, it would be the new insertion sort! Theoretically you could reduce the time by using a linked list and searching to the position it needs to be inserted and inserting it. In practice however you would be better off simply using a different sort, especially if you don't want your data in a linked list.
Selection sort is better when writing is expensive. Quicksort and Mergesort are faster on large data sets.
1 answer
#include
#include
#define MAX_ARY 10
void merge_sort(int x[], int end, int start);
int main(void) {
int ary[MAX_ARY];
int j = 0;
printf("\n\nEnter the elements to be sorted: \n");
for(j=0;j scanf("%d",&ary[j]);
/* array before mergesort */
printf("Before :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);
printf("\n");
merge_sort(ary, 0, MAX_ARY - 1);
/* array after mergesort */
printf("After Merge Sort :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);
printf("\n");
getch();
}
/* Method to implement Merge Sort*/
void merge_sort(int x[], int end, int start) {
int j = 0;
const int size = start - end + 1;
int mid = 0;
int mrg1 = 0;
int mrg2 = 0;
int executing[MAX_ARY];
if(end == start)
return;
mid = (end + start) / 2;
merge_sort(x, end, mid);
merge_sort(x, mid + 1, start);
for(j = 0; j < size; j++)
executing[j] = x[end + j];
mrg1 = 0;
mrg2 = mid - end + 1;
for(j = 0; j < size; j++) {
if(mrg2 <= start - end)
if(mrg1 <= mid - end)
if(executing[mrg1] > executing[mrg2])
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
else
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
}
}
;j++)>
1 answer
The MERGESORT algorithm performs atmost a single call to any pair of indices
of the array that is being sorted. In otherwords, the subproblems do not
overlap and therefore memoization will not improve the running time.
otherwise........take the look at following:
It does not have the Overlapping Subproblems property.
(Not re-visiting subproblems.)
Needs lot of space to store solutions of subproblems.
Overlapping sub-problems property is as follows:
We accidentally recalculate the same problem twice or more.
1 answer
#include <stdio.h>
void merge_sort(int [], int, int);
void merge_array(int [], int, int, int);
main()
{
int a[50], n, i;
printf("\nEnter size of an array: ");
scanf("%d", &n);
printf("\nEnter elements of an array:\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
merge_sort(a, 0, n-1);
printf("\n\nAfter sorting:\n");
for(i=0; i<n; i++)
printf("\n%d", a[i]);
getch();
}
void merge_sort(int a[], int beg, int end)
{
int mid;
if (beg < end)
{
mid = (beg+end)/2;
merge_sort(a, beg, mid);
merge_sort(a, mid+1, end);
merge_array(a, beg, mid, end);
}
}www.eazynotes.com Gursharan Singh Tatla Page No. 2
void merge_array(int a[], int beg, int mid, int end)
{
int i, left_end, num, temp, j, k, b[50];
for(i=beg; i<=end; i++)
b[i] = a[i];
i = beg;
j = mid+1;
k = beg;
while ((i<=mid) && (j<=end))
{
if (b[i] <= b[j])
{
a[k] = b[i];
i++; k++;
}
else
{
a[k] = b[j];
j++; k++;
}
}
if (i <= mid)
{
while (i <= mid)
{
a[k] = b[i];
i++; k++;
}
}
else
{
while (j <= end)
{
a[k] = b[j];
j++; k++;
}
}
}
3 answers
Selection sort has no end conditions built in, so it will always compare every element with every other element.
This gives it a best-, worst-, and average-case complexity of O(n2).
8 answers
Quicksort will usually be the best performing sort. However, quicksort has a worst-case time complexity of O(n2), which may not be reasonable in a real world application. Heapsort is often used in place of quicksort in these cases, as it has a worst-case of O(n log n).
The last of the "big three" sorts is mergesort, which excels in a few areas. Mergesort is trivially easy to parallelize, which is increasingly useful as multi-CPU machines become more and more common. Mergesort is also a stable sort, which may or may not be useful for a given application.
2 answers
Let me give an example of MergeSort from my real life. I have two sets of graded papers from the same class and both sets are alphabetized. If I want to merge the two piles into one, I don't have to start all over again, I can use the work that's already been down alphabetizing them separately. The first paper on the merged list has to be either the top paper from list #1 or the top from list #2. I take that paper and put it on a new stack face down. Now I make the comparison between the new two papers on top of the stacks and put it face down on the new stack, again and again, until all the papers are on the new stack face down. Once one of the original stacks is depleted, there are no more comparisons to be made and I can put the rest of the remaining stack face down on top of the merged stack, turn it back face up and it is completely sorted.
1 answer
Statistically both MergeSort and QuickSort have the same average case time: O(nlog(n)); However there are various differences.
Most implementations of Mergesort, require additional scratch space, which could bash the performance. The pros of Mergesort are: it is a stable sort, and there is no worst-case scenario.
Quicksort is often implemented inplace thus saving the performance and memory by not creating extra storage space. However the performance falls on already sorted/almost sorted lists if the pivot is not randomized.
== ==
7 answers
Writing your own programming language is an incredibly ambitious, and almost unachievable, goal. You won't be able to do this on your own unless you are a hardworking genius. Writing a programming language entails making a way for the average individual to communicate with electronic equipment. To make a language you need a working knowledge of the electronics you are making the language for - either a CPU or a smaller chip.
When you understand how all the 1s and 0s (off and on, respectively) work, then you can combine them to create definitions for different programming words (i.e. Add, Subtract, If/Then, etc.).
An alternative is to base your programming language off another programming language. In other words, if you would like to simplify a language like C then you would need a working knowledge of that language. From that knowledge, you can create definitions which can be used to invoke C code.
There are programs to create compilers -- YACC is the most well known of them (use google for details).
5 answers
By understanding the time and space complexities of sorting algorithms, you will better understand how a particular algorithm will scale with increased data to sort.
* Bubble sort is O(N2). The number of Ops should come out <= 512 * 512 = 262144 * Quicksort is O(2N log N) on the average but can degenerate to (N2)/2 in the worst case (try the ordered data set on quicksort). Quicksort is recursive and needs a lot of stack space. * Shell sort (named for Mr. Shell) is less than O(N4/3) for this implementation. Shell sort is iterative and doesn't require much extra memory. * Merge sort is O( N log N) for all data sets, so while it is slower than the best case for quicksort, it doesn't have degenerate cases. It needs additional storage equal to the size of the input array and it is recursive so it needs stack space. * Heap sort is guaranteed to be O(N log N), doesn't degenerate like quicksort and doesn't use extra memory like mergesort, but its implementation has more operations so on average its not as good as quicksort.
3 answers
Sorting, in the realm of computer science, refers to arranging a list of elements in a particular order—be it ascending, descending, or any other specific sequence. It's a fundamental operation, much like the alphabetizing of books in a library or the ranking of students based on their grades.
Why is sorting so crucial? At its core, sorting aids in data retrieval. If you've ever used a dictionary, you'll appreciate how much quicker it is to find a word when everything is alphabetically ordered. Similarly, in computing, searching for an item in a sorted list is exponentially faster than in an unsorted one.
Several algorithms exist for sorting, each with its nuances. From the classic Bubble Sort, which repeatedly steps through the list and swaps adjacent items if they're in the wrong order, to the more sophisticated algorithms like QuickSort and MergeSort, the world of sorting is vast and varied.
But the benefits of sorting extend beyond just efficient data retrieval. Sorting aids in data visualization. When data is orderly, patterns and anomalies become more evident. This is why data analysts often sort datasets before diving into deeper analyses.
Furthermore, sorting paves the way for better resource utilization. Consider a scenario where a company needs to send promotional emails to its top 100 customers. If the customer database is sorted by purchase amount, extracting the top 100 becomes a straightforward task. Without sorting, the company might have to sift through thousands of records, consuming both time and computational resources.
In the digital age, where data is continuously generated, the importance of sorting cannot be overstated. It's an operation that underpins many functions, from database management to online shopping. By arranging data methodically, sorting ensures that information is not just stored, but is also accessible, understandable, and actionable.
2 answers
There are a great many sorts, Mergesort and Quicksort being among the most popular. These both have on the order of n*log n expected case runtime, and while Quicksort can get as bad as n^2, this is unlikely due to most implementations using a random pivot.
If you can make the assumption that ONLY NUMBERS will be sorted, you can use RadixSort, which is the fastest known sort for numbers.
As for how to sort in particular programming languages, consult your local API (in C++ it is in the STL's "algorithm" include file).
5 answers
• Write Your Own Programs
o Write your own C program to implement the atoi() function
o Implement the memmove() function. What is the difference between the memmove() and memcpy() function?
o Write C code to implement the strstr() (search for a substring) function.
o Write your own printf() function in C
o Implement the strcpy() function.
o Implement the strcmp(str1, str2) function.
o Implement the substr() function in C.
o Write your own copy() function
o Write C programs to implement the toupper() and the isupper() functions
o Write a C program to implement your own strdup() function.
o Write a C program to implement the strlen() function
o Write your own strcat() function
• C
o Write a C program to swap two variables without using a temporary variable
o What is the 8 queens problem? Write a C program to solve it.
o Write a C program to print a square matrix helically.
o Write a C program to reverse a string
o Write a C program to reverse the words in a sentence in place.
o Write a C program generate permutations.
o Write a C program for calculating the factorial of a number
o Write a C program to calculate pow(x,n)?
o Write a C program which does wildcard pattern matching algorithm
o How do you calculate the maximum subarray of a list of numbers?
o How to generate Fibonacci numbers? How to find out if a given number is a Fibonacci number or not? Write C programs to do both.
o Solve the Rat In A Maze problem using backtracking.
o What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-endian or little endian? How can we convert from one to another?
o Write C code to solve the Tower of Hanoi problem.
o Write C code to return a string from a function
o Write a C program which produces its own source code as its output
o Write a C progam to convert from decimal to any base (binary, hex, oct etc...)
o Write C code to check if an integer is a power of 2 or not in a single line?
o Write a C program to find the GCD of two numbers.
o Finding a duplicated integer problem
o Write code to remove duplicates in a sorted array.
o Find the maximum of three integers using the ternary operator.
o How do you initialize a pointer inside a function?
o Write C code to dynamically allocate one, two and three dimensional arrays (using malloc())
o How would you find the size of structure without using sizeof()?
o Write a C program to multiply two matrices.
o Write a C program to check for palindromes.
o Write a C program to convert a decimal number into a binary number.
o Write C code to implement the Binary Search algorithm.
o Wite code to evaluate a polynomial.
o Write code to add two polynomials
o Write a program to add two long positive numbers (each represented by linked lists).
o How do you compare floating point numbers?
o What's a good way to implement complex numbers in C?
o How can I display a percentage-done indication on the screen?
o Write a program to check if a given year is a leap year or not?
o Is there something we can do in C but not in C++?
o How to swap the two nibbles in a byte ?
o How to scan a string till we hit a new line using scanf()?
o Write pseudocode to compare versions (like 115.10.1 vs 115.11.5).
o How do you get the line numbers in C?
o How to fast multiply a number by 7?
o Write a simple piece of code to split a string at equal intervals
o Is there a way to multiply matrices in lesser than o(n^3) time complexity?
o How do you find out if a machine is 32 bit or 64 bit?
o Write a program to have the output go two places at once (to the screen and to a file also)
o Write code to round numbers
o How can we sum the digits of a given number in single statement?
o Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?
o Write a program to merge two arrays in sorted order, so that if an integer is in both the arrays, it gets added into the final array only once. *
o Write a program to check if the stack grows up or down
o How to add two numbers without using the plus operator?
o How to generate prime numbers? How to generate the next prime after a given prime?
o Write a program to print numbers from 1 to 100 without using loops!
o Write your own trim() or squeeze() function to remove the spaces from a string.
o Write your own random number generator function in C.*
o Write your own sqrt() function in C*
• Sorting Techniques Programs
o What is heap sort?
o What is the difference between Merge Sort and Quick sort?
o Give pseudocode for the mergesort algorithm
o Implement the bubble sort algorithm. How can it be improved? Write the code for selection sort, quick sort, insertion sort.
o How can I sort things that are too large to bring into memory?
• C Pointers Programs
o What does *p++ do? Does it increment p or the value pointed by p?
o What is a NULL pointer? How is it different from an unitialized pointer? How is a NULL pointer defined?
o What is a null pointer assignment error?
o Does an array always get converted to a pointer? What is the difference between arr and &arr? How does one declare a pointer to an entire array?
o Is the cast to malloc() required at all?
o What does malloc() , calloc(), realloc(), free() do? What are the common problems with malloc()? Is there a way to find out how much memory a pointer was allocated?
o What's the difference between const char *p, char * const p and const char * const p?
o What is a void pointer? Why can't we perform arithmetic on a void * pointer?
o What do Segmentation fault, access violation, core dump and Bus error mean?
o What is the difference between an array of pointers and a pointer to an array?
o What is a memory leak?
o What are brk() and sbrk() used for? How are they different from malloc()?
o What is a dangling pointer? What are reference counters with respect to pointers?
o What do pointers contain?
o Is *(*(p+i)+j) is equivalent to p[i][j]? Is num[i] operator?
o Can we pass constant values to functions which accept structure arguments?
o How does one use fread() and fwrite()? Can we read/write structures to/from files?
o Why do structures get padded? Why does sizeof() return a larger size?
o Can we determine the offset of a field within a structure and directly access that element?
o What are bit fields in structures?
o What is a union? Where does one use unions? What are the limitations of unions?
• C Macros Programs
o How should we write a multi-statement macro?
o How can I write a macro which takes a variable number of arguments?
o What is the token pasting operator and stringizing operator in C?
o Define a macro called SQR which squares a number.
• C Headers Programs
o What should go in header files? How to prevent a header file being included twice? Whats wrong with including more headers?
o Is there a limit on the number of characters in the name of a header file?
o Is it acceptable to declare/define a variable in a C header?
• C File operations Programs
o How do stat(), fstat(), vstat() work? How to check whether a file exists?
o How can I insert or delete a line (or record) in the middle of a file?
o How can I recover the file name using its file descriptor?
o How can I delete a file? How do I copy files? How can I read a directory in a C program?
o Whats the use of fopen(), fclose(), fprintf(), getc(), putc(), getw(), putw(), fscanf(), feof(), ftell(), fseek(), rewind(), fread(), fwrite(), fgets(), fputs(), freopen(), fflush(), ungetc()?
o How to check if a file is a binary file or an ascii file?
• C Declarations and Definitions Programs
o What is the difference between char *a and char a[]?
o How can I declare an array with only one element and still access elements beyond the first element (in a valid fashion)?
o What is the difference between enumeration variables and the preprocessor #defines?
• C Functions - built-in Programs
o Whats the difference between gets() and fgets()? Whats the correct way to use fgets() when reading a file?
o How can I have a variable field width with printf?
o How can I specify a variable width in a scanf() format string?
o How can I convert numbers to strings (the opposite of atoi)?
o Why should one use strncpy() and not strcpy()? What are the problems with strncpy()?
o How does the function strtok() work?
o Why do we get the floating point formats not linked error?
o Why do some people put void cast before each call to printf()?
o What is assert() and when would I use it?
o What do memcpy(), memchr(), memcmp(), memset(), strdup(), strncat(), strcmp(), strncmp(), strcpy(), strncpy(), strlen(), strchr(), strchr(), strpbrk(), strspn(), strcspn(), strtok() do?
o What does alloca() do?
o Can you compare two strings like string1==string2? Why do we need strcmp()?
o What does printf() return?
o What do setjmp() and longjump() functions do?
• C Functions - The main function Programs
o Whats the prototype of main()? Can main() return a structure?
o Is exit(status) equivalent to returning the same status from main()?
o Can main() be called recursively?
o How to print the arguments received by main()?
1 answer