473,753 Members | 7,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mergesort - strange output

rkk
Hi,

My mergesort program is below. There is a small piece of logical
error/bug in this code which I can't figure out, as a result the output
array isn't completely sorted. Requesting your help to resolve this
problem. Thanks in advance.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef int (*CompareFunc)( const void*,const void*);

void MergeSort(void *array[],int left,int right,CompareFu nc compare);
void Merge(void *array[],int left,int mid,int right,CompareFu nc
compare);
int IntCompare(cons t void *a,const void *b);
int StrCompare(cons t void *a,const void *b);

void MergeSort(void *array[],int left,int right,CompareFu nc compare)
{
int mid;
if ( left >= right ) return;
mid = (left + right)/2;
MergeSort(array ,left,mid,compa re);
MergeSort(array ,mid + 1,right,compare );
Merge(array,lef t,mid,right,com pare);
}

void Merge(void *array[],int left,int mid,int right,CompareFu nc
compare)
{
int numElements = right - left + 1;
void **aux;
int lowerBound = left,upperBound = mid + 1,index = 0;
aux = malloc(numEleme nts * sizeof &array[0]);
if(aux == NULL) {
fprintf(stderr, "Merge: %s\n","malloc failed");
return;
}
while ( lowerBound <= mid && upperBound <= right )
{
if(compare(&arr ay[lowerBound],&array[upperBound]) < 0) {
aux[index++] = array[lowerBound++];
} else {
aux[index++] = array[upperBound++];
}
}
while ( lowerBound <= mid ) aux[index++] = array[lowerBound++];
while ( upperBound <= right) aux[index++] = array[upperBound++];

for(index = left ; index < numElements; index++)
array[index] = aux[index];
free(aux);
}

int IntCompare(cons t void *a,const void *b)
{
const int *ia = (const int*) a;
const int *ib = (const int*) b;
return ( (*ia *ib) - (*ia < *ib) );
}

int StrCompare(cons t void *a,const void *b)
{
return strcmp(*(char **) a, *(char **) b);
}

int main()
{
int i;
int iArray[] = {6,3,2,1,4,5,7, 9,10,11,13,12,8 ,14};
int sizeOfArray = sizeof iArray/sizeof iArray[0];
MergeSort((void **)iArray,0,(si zeOfArray-1),IntCompare);
for(i=0; i < sizeOfArray; i++)
printf("%d ", iArray[i] );
printf("\n");
return 0;
}

Here is how I compile:
$ gcc -g -o mergesort mergesort.c

Here is the output:
$ ./mergesort
2 1 3 4 5 6 7 9 10 11 13 12 8 14

Clearly the output isn't completely sorted. Kindly help.

Regards
Kalyan

Sep 30 '06 #1
2 3562
On 30 Sep 2006 07:18:17 -0700, "rkk" <te*******@yaho o.comwrote:
>Hi,

My mergesort program is below. There is a small piece of logical
error/bug in this code which I can't figure out, as a result the output
array isn't completely sorted. Requesting your help to resolve this
problem. Thanks in advance.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef int (*CompareFunc)( const void*,const void*);

void MergeSort(void *array[],int left,int right,CompareFu nc compare);
void Merge(void *array[],int left,int mid,int right,CompareFu nc
compare);
int IntCompare(cons t void *a,const void *b);
int StrCompare(cons t void *a,const void *b);

void MergeSort(void *array[],int left,int right,CompareFu nc compare)
{
int mid;
if ( left >= right ) return;
mid = (left + right)/2;
MergeSort(array ,left,mid,compa re);
MergeSort(array ,mid + 1,right,compare );
Merge(array,lef t,mid,right,com pare);
}

void Merge(void *array[],int left,int mid,int right,CompareFu nc
compare)
{
int numElements = right - left + 1;
void **aux;
int lowerBound = left,upperBound = mid + 1,index = 0;
aux = malloc(numEleme nts * sizeof &array[0]);
Conceptually, array is an array of void*. array[0] is the first void*
in the array. &array[0] has type pointer to void* which is expressed
as void**.

aux is a void**. The thing it points to must be a void*. If
sizeof(void*) sizeof(void**) on your system, you are not allocating
enough space.

Eliminate this problem by using sizeof *aux.
> if(aux == NULL) {
fprintf(stderr, "Merge: %s\n","malloc failed");
return;
}
while ( lowerBound <= mid && upperBound <= right )
{
if(compare(&arr ay[lowerBound],&array[upperBound]) < 0) {
aux[index++] = array[lowerBound++];
} else {
aux[index++] = array[upperBound++];
}
}
while ( lowerBound <= mid ) aux[index++] = array[lowerBound++];
while ( upperBound <= right) aux[index++] = array[upperBound++];

for(index = left ; index < numElements; index++)
array[index] = aux[index];
free(aux);
}

int IntCompare(cons t void *a,const void *b)
{
const int *ia = (const int*) a;
const int *ib = (const int*) b;
return ( (*ia *ib) - (*ia < *ib) );
}

int StrCompare(cons t void *a,const void *b)
{
return strcmp(*(char **) a, *(char **) b);
}

int main()
int main(void) is preferable.
>{
int i;
int iArray[] = {6,3,2,1,4,5,7, 9,10,11,13,12,8 ,14};
int sizeOfArray = sizeof iArray/sizeof iArray[0];
MergeSort((void **)iArray,0,(si zeOfArray-1),IntCompare);
Here you potentially invoke undefined behavior. You pass the address
of iArray, cast to the correct type, to MergeSort. MergeSort takes
this address and treats the objects (of type int) that it finds there
as having type void*.

Do you know for a fact that an int is properly aligned for a
void*?

Do you know for a fact that they both have the same size? If
not, when MergeSort references array[1] it may actually access
iArray[2] (consider a system with 16-bit int and 32-bit pointers).

Do you know for a fact that the int values are valid for void*?
MerseSort does evaluate them as void* when it copies the values in and
out of aux.
> for(i=0; i < sizeOfArray; i++)
printf("%d ", iArray[i] );
printf("\n");
return 0;
}

Here is how I compile:
$ gcc -g -o mergesort mergesort.c

Here is the output:
$ ./mergesort
2 1 3 4 5 6 7 9 10 11 13 12 8 14

Clearly the output isn't completely sorted. Kindly help.

Regards
Kalyan

Remove del for email
Sep 30 '06 #2
rkk wrote:
>
My mergesort program is below. There is a small piece of logical
error/bug in this code which I can't figure out, as a result the output
array isn't completely sorted. Requesting your help to resolve this
problem. Thanks in advance.
Arrays are easily handled with the standard qsort routine.
Mergesort is better suited for linked lists. You can find an
example of such in the wdfreq demo for hashlib. See the functions
splitlist, mergelists, mergesort. About 60 lines, including fairly
extensive commentary. The whole thing is available at:

<http://cbfalconer.home .att.net/download/>

--
Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/(C99)
<http://www.dinkumware. com/refxc.html (C-library}
<http://gcc.gnu.org/onlinedocs/ (GNU docs)
<http://clc-wiki.net (C-info)
Oct 1 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3649
by: Jochus | last post by:
Today, I've programmed Mergesort. And it works very good :-)! But now, the teacher said that you could use Mergesort to count the amount of inversions. This is what I found on the internet: --- Note: Merge Sort can be slightly modified to count inversion index (i.e. bubble sort swaps) in O(n log n) time. When the right partition goes in
1
3381
by: Jamal | last post by:
I am working on binary files of struct ACTIONS I have a recursive qsort/mergesort hybrid that 1) i'm not a 100% sure works correctly 2) would like to convert to iteration Any comments or suggestion for improvements or conversion to iteration would be much appreciated
6
2881
by: Jamal | last post by:
I am working on binary files of struct ACTIONS I have a recursive qsort/mergesort hybrid that 1) i'm not a 100% sure works correctly 2) would like to convert to iteration Any comments or suggestion for improvements or conversion to iteration would be much appreciated
1
2249
by: ben81 | last post by:
Hi, the following code is adopted PseudoCode from Introduction to Algorithms (Cormen et al). For some reason it can't get it to work. I always get a index of out bounds exception or some weird result. Secondly I'd like to know how to write this more pythonic. TIA. import random import listutil import unittest
51
8645
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort for linked lists, I couldn't find one. I read something about Mcilroy's "Optimistic Merge Sort" and studied some implementation, but they were for arrays. Does anybody know if Mcilroys optimization is applicable to truly linked lists at all?
5
1843
by: Chad | last post by:
I was looking at some old posts in comp.lang.c and found the following http://groups.google.com/group/comp.lang.c/browse_thread/thread/d26abbdf4d99abd9/b3b5046326994e18?hl=en&lnk=gst&q=recurrence+relation#b3b5046326994e18 I have some questions regarding the post. First, and I quote "Given an algorithm with loops or recursive calls, the way you find a big-O equivalence class for that algorithm is to write down a
0
9072
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8896
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9653
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9451
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8328
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4771
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2872
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2284
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.