473,766 Members | 2,060 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterative Merge Sort Using Circular Linked List

// Merge sort using circular linked list

// By Jason Hall <bo*******@yaho o.com>

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

//#define debug
#define print_answer
//#define print_time

#define major_size 1048576
int mergesort(int *buffer, int size);
int merge(int *outbuffer, int *in1, int size1, int *in2, int size2);

struct merger
{
int size;
merger *next;
int *buffer;
};
int main(void)
{
int *buffer;
int i;
time_t seed, begin, end;
buffer=(int *) malloc(sizeof(i nt) *major_size);
time(&seed);
srand(seed);
for(i=0;i<major _size;i++)
{
//buffer[i]=rand()%100;
buffer[i]=major_size-i;
}
time(&begin);
mergesort(buffe r, major_size);
time(&end);
#ifdef print_time
printf("Time is %i\n", end-begin);
#endif
#ifdef print_answer

for(i=0;i<major _size;i++)
{
printf("%i ", buffer[i]);
}
#endif
printf("\n");
free(buffer);
}
int mergesort(int *buffer, int size)
{
merger *first, *temp, *temp2;
int i, *tempbuffer, entnow, remain, sum, entries, x, *temp3;

#ifdef debug
int debugcount=2;
#endif
entnow=size/2;
remain=size%2;
sum=entnow+rema in;
entries=entnow;
do
{
entnow=sum/2;
remain=sum%2;
sum=entnow+rema in;
entries+=entnow ;
}while(entnow!= 1 || remain!=0);

if(size<=1)
{
return -1;
}
if(size==2)
{
if(buffer[0]>buffer[1])
{
x=buffer[1];
buffer[1]=buffer[0];
buffer[0]=x;
}
}

first=(merger *) malloc(sizeof(m erger));
temp=first;
if(size%2==0)
{
for(i=0;i<size-2;i+=2)
{
tempbuffer=(int *) malloc(sizeof(i nt)*2);
merge(tempbuffe r, buffer+i, 1, buffer+i+1, 1);
temp->buffer=tempbuf fer;
temp->next=(merger *) malloc(sizeof(m erger));
temp->size=2;
temp=temp->next;
}
tempbuffer=(int *) malloc(sizeof(i nt)*2);
merge(tempbuffe r, buffer+size-2, 1, buffer+size-1, 1);
temp->buffer=tempbuf fer;
temp->next=first;
temp->size=2;
}
else
{
for(i=0;i<size-1;i+=2)
{
tempbuffer=(int *) malloc(sizeof(i nt)*2);
merge(tempbuffe r, buffer+i, 1, buffer+i+1, 1);
temp->buffer=tempbuf fer;
temp->next=(merger *) malloc(sizeof(m erger));
temp->size=2;
temp=temp->next;
//entries++;
}
tempbuffer=(int *) malloc(sizeof(i nt));
tempbuffer[0]=buffer[size-1];
temp->buffer=tempbuf fer;
temp->next=first;
temp->size=1;
//entries++;

}
for(i=0;i<entri es-3;i++)
{
tempbuffer=(int *) malloc(sizeof(i nt)*(temp->size+temp->next->size));
merge(tempbuffe r, temp->buffer, temp->size, temp->next->buffer, temp->next->size);
temp->size=temp->size+temp->next->size;
free(temp->buffer);
free(temp->next->buffer);
temp->buffer=tempbuf fer;
temp2=temp->next;
temp->next=temp->next->next;
free(temp2);
temp=temp->next;
entries--;
#ifdef debug
printf("Level %i\n", debugcount);
debugcount++;
#endif
}
merge(buffer, temp->buffer, temp->size, temp->next->buffer, temp->next->size);
#ifdef debug
printf("Level %i\n", debugcount);
#endif

free(temp->next->buffer);
free(temp->next);
free(temp->buffer);
free(temp);
}
int merge(int *outbuffer, int *in1, int size1, int *in2, int size2)
{
int i=0,j=0, k=0;
while(i<size1 && j<size2)
{
if(in1[i]<=in2[j])
{
outbuffer[k]=in1[i];
i++;
}
else
{
outbuffer[k]=in2[j];
j++;
}
k++;
}
if(i<size1)
{
while(i<size1)
{
outbuffer[k]=in1[i];
i++;
k++;
}
}
else
{
while(j<size2)
{
outbuffer[k]=in2[j];
j++;
k++;
}
}
return 0;
}
Nov 14 '05 #1
1 12844
Booser wrote:

// Merge sort using circular linked list

// By Jason Hall <bo*******@yaho o.com>


Seems somewhat long to me. Try this, lists need not be circular.

/* List handling, reversal, sort, merge, split */
/* file listops.h */
/* By C.B. Falconer. Public Domain, use as you wish */
/* Attribution appreciated. */
/* =============== === 30 April, 2001 =============== === */

#ifndef listops_h_
#define listops_h_

#include <stddef.h> /* NULL */
#include <iso646.h> /* not, and */

/* The bare minimum to form a linked list */
typedef struct node {
struct node *next;
void *data;
} node, *nodeptr;

/* =============== =============== =============== ========== */
/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
nodeptr revlist(nodeptr root);

/* =============== =============== =============== ========== */
/* split list p into 2 nearly equal lists, return 2nd part */
nodeptr splitlist(nodep tr p);

/* =============== =============== == */
/* Merge two ordered lists into one */
nodeptr mergelists(node ptr p1, nodeptr p2,
int (*cmp)(void *, void*)); /* compare */

/* =============== =============== =============== ===== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodep tr root,
int (*cmp)(void *, void*)); /* compare */

#endif

/* end listops.h */

/* List handling, reversal, sort, merge, split */
/* file listops.c */
/* By C.B. Falconer. Public Domain, use as you wish */
/* Attribution appreciated. */
/* =============== === 30 April, 2001 =============== === */

#include "listops.h"

/* =============== =============== =============== ========== */
/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
nodeptr revlist(nodeptr root)
{
nodeptr curr, nxt;

if (root) { /* non-empty list */
curr = root->next;
root->next = NULL; /* terminate new list */
while (curr) {
nxt = curr->next; /* save for walk */
curr->next = root; /* relink */
root = curr; /* save for next relink */
curr = nxt; /* walk onward */
}
}
/* else empty list is its own reverse; */
return root;
} /* revlist */

/* =============== =============== =============== ========== */
/* split list p into 2 nearly equal lists, return 2nd part */
nodeptr splitlist(nodep tr p)
{
nodeptr p1, p2, p3;

p1 = p2 = p3 = p;
if (not p) return NULL;
do {
p3 = p2;
p2 = p2->next; /* advance 1 */
p1 = p1->next;
if (p1) p1 = p1->next; /* advance 2 */
} while (p1);

/* now form new list after p2 */
p3->next = NULL; /* terminate 1st half */
return p2;
} /* splitlist */

/* =============== =============== == */
/* Merge two ordered lists into one */
nodeptr mergelists(node ptr p1, nodeptr p2,
int (*cmp)(void *, void*)) /* compare */
{
node n;
nodeptr p;

p = &n;
n.next = p;

while (p1 and p2) {
if (cmp(p1, p2) <= 0) {
p->next = p1; p = p1; p1 = p1->next;
}
else {
p->next = p2; p = p2; p2 = p2->next;
}
}
/* at least one list now empty, copy other */
/* one or both of these operations is null */
if (p1) p->next = p1;
if (p2) p->next = p2;

/* check for empty lists */
if (n.next == &n) return NULL;
return n.next;
} /* mergelists */

/* =============== =============== =============== ===== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodep tr root,
int (*cmp)(void *, void*)) /* compare */
{
nodeptr p;

if (root and root->next) { /* 2 up items in list */
p = splitlist(root) ; /* alters list root */
root = mergelists(merg esort(root, cmp),
mergesort( p, cmp),
cmp);
}
/* else the unit or empty list is already sorted */

return root;
} /* mergesort */

/* end listops.c */

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #2

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

Similar topics

6
16134
by: Julia | last post by:
I am trying to sort a linked list using insertion sort. I have seen a lot of ways to get around this problem but no time-efficient and space-efficient solution. This is what I have so far: struct node { int x; struct node *next; };
7
14255
by: Zeba | last post by:
Hi, I have to write program in C# to merge sort a linked list (doubly linked). Is it true that the best way to do it is copy it into an array, sort it and then convert back ? I'm new to C#, but I tried to develop a merge sort program myself, but have got stuck with a Null reference exception for the pos variable in merge function. Also I wrote a function to get the actual nodes from teh index values before calling merge function. Is...
2
3549
nabh4u
by: nabh4u | last post by:
hi friends, i have a program where i have to sort a double linked list using merge sort. i am having problem with changing the pointers of the list, like the previous and the next pointers of a node. i am unable to understand how can i change those. i tried something but that is not working. please help me as soon as possible as i have a deadline. here is a sample : int merge(low,mid,high) { int i,j,k; i=low; j=mid+1; list...
5
4491
by: Sarahger9 | last post by:
I am trying to generate a random vector of integers and sort them using merge sort. I am having trouble with the code. It is long, but I would appreciate if someone could take a look at it and see if the can help me, I've been working on it for days and am completely stuck. When I run the program, it just stops at the point where I call the mergesort. I believe the problem may be in the merge split, because when I cout the values for low,...
1
2636
by: vekka | last post by:
Hi! Could someone please help me to understand the use of merge algorithm(conceptually) with linked lists. What I want to do in the linked list function is: the function gets two inputs, i.e the pointers to the two smaller lists, then the function should able to merge these two together, and then return the head-pointer to this merged list. What happens in my case, is that I "lose" data when running it . My result is like this: Even OR...
0
1484
by: enigma08 | last post by:
I need to merge sort two linked lists, each has a header and the elements are all ints. I've tried adapting some generic code, but have run into a problem - errors that are similar to this one: split(AlgSet.LLAlgSet) in AlgSet.LLAlgSet cannot be applied to (Node<java.lang.Integer>) I see how that is happening as I'm giving it an element next instead of an actual list. Can someone help me out? I don't think it'll take much to fix it,...
2
6452
by: sathishc58 | last post by:
Hi Can anyone explain me the difference between circular linked list and looped linked list? 1) In Circular linked list Next part of last node will be pointing to the first nodes starting address. 2) What is meant by loop then? Thanks & Regards Sathish Kumar
4
1941
by: Tobiah | last post by:
I have a list of objects that generate code. Some of them depend on others being listed first, to satisfy dependencies of others. I wrote a cmp function something like this: def dep_cmp(ob1, ob2): if ob1.name in ob2.deps: return -1
5
6851
mithuncm
by: mithuncm | last post by:
hai all, any one, can you say how to merge two different linked list. I have 2 linked list where datas, & of corresponding time that datas send. I have to sort out datas according to time, to a single linked list. Do you have any idea?
0
9404
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
10008
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
9837
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
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
6651
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
5279
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...
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.