473,769 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help with sorting

Hey guys,

I am looking for some insight:
Given two sorted arrays of integers A and B, where array B has enough
extra room in it to hold the contents of both A and B. Merge array A
and B together such that the result is the sorted combination of the
two (do not remove duplicates) and the result resides in the B array.
I cannot perform any memory allocations to solve the problem.
Performance considerations should be taken into account in your
solution (so brute force method is not an option). Here is some
example data to help explain:

Array A: 4 7 10 15 17
Array B: 2 4 14 27 X X X X X

Where the X'es are unused slots in array B. The solution would end up
with B looking like this:

Array B: 2 4 4 7 10 14 15 17 27
Using the following function prototype:

void Merge (int *a, int na, int *b, int nb)

Where a and b point to the two arrays, na and nb are the number of
elements in each array. For array b, nb is the number of used
elements, not the size of the array. Assume array b is large enough to
hold the contents of a and b. Using the above example data na would be
5 and nb would be 4.

Also please specify the order of complexity for the algorithm you
chose to solve the problem.

My first thoughts are merge sort of course, although it requires your
to perform additional memory allocation. This leads to me an in
place merge sort.

What do you guys thinks? Any suggestions? Code isn't so important (i
can write that) but I am looking for help with the algorithm.
Thanks!
Nov 14 '05
27 2348
pete wrote:
Richard Heathfield wrote:
Simon Bachmann wrote:

<snip>
I would do something like this:

-you need two counters(ia ib):
one for a, one for b. their initial value is na respecively nb
-use this counters to compare the respective elements
of the two arrays
-copy the greather to the last (empty) element of b
-decrease the counter ia OR ib (ia if a[ia] > b[ib], ib otherwise)
-go on "filling up" b from the last element
towards the first, comparing a[ia] b[ib]

This way you need no additional memory allocation,
and work will be done with exactly na+nb passages.


I was about to complain that you would need to reserve
storage for ia and ib, but of course you can use na and nb,
which you get for free. Very neat.


I very much prefer the "pointer to element, size_t"
sorting function interface, which I got from Dann Corbit,
over the interface where everything is int and pointers to int,
for two reasons: 1 pedagogy, 2 practicality.

From a sorting algorithm point of view,
the objects which are used for book keeping inside the function,
like your ia and ib above, are conceptually,
completely different from the array elements which are also integers.


.... snip code etc. ...

Here is my version of the algorithm. The actual merge is 4 lines
of code. It is O(N), where N is the size of the merged array.

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

/* Simulating arrays to mergesort in place with strings */
/* blanks represent empty locations. The strlen represents */
/* the actual array capacity, which is fixed */

char aitem[] = "abde ";
char bitem[] = "acegjmpr ";
char citem[] = "acegjmpr ";
char ditem[] = "acegjmpr ";

#define UNUSED ' '

/* ----------------- */

void showitem(char *s, int index)
{
if (index >= 0) printf("[%d] ", index);
printf("\"%s\"\ n", s);
} /* showitem */

/* ----------------- */

void merge(char *new, char* into)
{
int intosize, intolgh, newlgh;

/* extract parameters */
intosize = strlen(into);
intolgh = strchr(into, UNUSED) - into;
newlgh = strchr(new, UNUSED) - new;

/* validate space available */
if (intosize < (intolgh + newlgh)) return; /* No room */
if (intosize > (intolgh + newlgh))
intosize = intolgh + newlgh;

/* The actual merge operation */
while (newlgh && (intosize > intolgh)) {
if (into[intolgh-1] > new[newlgh-1])
into[--intosize] = into[--intolgh];
else into[--intosize] = new[--newlgh];
}
} /* merge */

/* ----------------- */

int main(void)
{
showitem(aitem, -1); showitem(bitem, -1);
merge(aitem, /* into */ bitem);
showitem(bitem, -1);
showitem(aitem, -1); showitem(citem, -1);
merge(aitem, /* into */ citem);
showitem(citem, -1);
showitem(aitem, -1); showitem(ditem, -1);
merge(aitem, /* into */ ditem);
showitem(ditem, -1);
return 0;
}

--
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 #21
<<<Way to post the Microsoft interview question. Hope they don't use google!

We do actually. Google is quite helpful. :) Not to post for a job, but since it was brought up here, if anyone thinks they have what it takes to answer a question like this (on their own)and is interested in working for Microsoft, feel free to e-mail me at to*****@microso ft.com. :)

Gretchen Ledgard
Sr. Talent Scout
Microsoft Corporation

Nov 14 '05 #22
<<<Way to post the Microsoft interview question. Hope they don't use google!

We do actually. Google is quite helpful. :) Not to post for a job, but since it was brought up here, if anyone thinks they have what it takes to answer a question like this (on their own)and is interested in working for Microsoft, feel free to e-mail me at to*****@microso ft.com. :)

Gretchen Ledgard
Sr. Talent Scout
Microsoft Corporation

Nov 14 '05 #23
<<<Way to post the Microsoft interview question. Hope they don't use google!

We do actually. Google is quite helpful. :) Not to post for a job, but since it was brought up here, if anyone thinks they have what it takes to answer a question like this (on their own)and is interested in working for Microsoft, feel free to e-mail me at to*****@microso ft.com. :)

Gretchen Ledgard
Sr. Talent Scout
Microsoft Corporation

Nov 14 '05 #24
<<<Way to post the Microsoft interview question. Hope they don't use google!

We do actually. Google is quite helpful. :) Not to post for a job, but since it was brought up here, if anyone thinks they have what it takes to answer a question like this (on their own)and is interested in working for Microsoft, feel free to e-mail me at to*****@microso ft.com. :)

Gretchen Ledgard
Sr. Talent Scout
Microsoft Corporation

Nov 14 '05 #25
User error. :) Didn't mean to spam with 4 posts.

Apologies again,
Gretchen

Nov 14 '05 #26
On Tue, 10 Feb 2004 20:00:43 -0600, Gledgard <to*****@micros oft.com> wrote:


<<<Way to post the Microsoft interview question. Hope they don't use google!

We do actually. Google is quite helpful. :) Not to post for a job, but since it was brought up here, if anyone thinks they have what it takes to answer a question like this (on their own)and is interested in working for Microsoft, feel free to e-mail me at to*****@microso ft.com. :)

Gretchen Ledgard
Sr. Talent Scout
Microsoft Corporation

Sorry. Working for Microsoft is way below cleaning sewers on my list of
preferred jobs.

You couldn't pay me to work with or for that grotesque OS.

I remember fondly the day that I wrote random numbers 25X over the parition
that was home to XPernicious.
Linux/UNIX are where it's at, but SCO can kiss my ass.

How typical of a M$ employee (if you aren't just a fucking troll) to
have a deceptive subject on their post.
AC
--
ed(1)
Check out the original tutorials by Brian W. Kernighan:
----- http://tinyurl.com/2uprx -----
If it's good enough for BWK, it's good enough for me.
Nov 14 '05 #27
[text re-flowed]

Gledgard wrote:
<<<Way to post the Microsoft interview question. Hope they don't use
google!

We do actually. Google is quite helpful. :) Not to post for a job, but
since it was brought up here, if anyone thinks they have what it takes to
answer a question like this (on their own)and is interested in working for
Microsoft, feel free to e-mail me at <email address elided>


Please adjust your news client's line length setting. There is often some
dispute in Usenet about whether 60, or 65, or 72, or some other comparable
number is the Right Maximum Length for a Usenet line, but I think it's
generally accepted that 278 is way too long.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #28

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

Similar topics

4
2533
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys() sorted_feature_vector.sort() #feature_vector.keys()=sorted_feature_vector
2
3078
by: D. Roshani | last post by:
Hello ! I wonder if any one can help me to create a cosomize sorting order (as Macro or added small program in c++ or c# which does this work) in a Access Database contaning one table only words encoded in ISO-8859-1 A a B b C c D d E e É é F f G g H h I i Í í J j 1 2 3 4 5 6 7 8 9 10 11 12 Jh jh K k L l ll M m N n O o P p Q q R r rr S s...
3
4037
by: Neil Hindry | last post by:
I wonder if you can help me. I have setup an address-book database in Access XP. I have the first name & surname as separate fields. As I wanted to sort my database by surname and then by first name I had surname before first name when I created the fields of my database.. To do the sort (in table view) I highlighted the two columns (fields), in this case surname and first name, and selected sort. Access then sorted the database by...
1
2644
by: aredo3604gif | last post by:
On Sun, 10 Apr 2005 19:46:32 GMT, aredo3604gif@yahoo.com wrote: >The user can dynamically enter and change the rule connection between >objects. The rule is a "<" and so given two objects: >a < b simply means that b < a can't be set, also it must be a != b. >And with three objects a < b , b < c means a < c > >I studied Quick Union Find algorithms a bit and if I understood them >correctly, once the user gives the input setting the...
3
2397
by: Don | last post by:
I have a "Report" that is created from a "Form". It prints a list of items, you may consider it a shopping list. In any event I use to run this in alphabetical order but have since decided to run it as it comes from the form (random order). My problem is I don't know how to make this happen. The report is sorted in ascending order and I don't know how to change that. I see only two options, ascending or descending. Can you help?...
2
2903
by: rookiejavadude | last post by:
I'm have most of my java script done but can not figure out how to add a few buttons. I need to add a delete and add buttong to my existing java program. Not sure were to add it on how. Can anyone help? my script is below. thank you import java.awt.*; //import all java.awt import java.awt.event.*; //import all java.awt.event import java.util.*; //import all java.util import javax.swing.*; //import all javax.swing class Product...
1
2180
by: Ahmed Yasser | last post by:
Hi all, i have a problem with the datagridview sorting, the problem is a bit complicated so i hope i can describe in the following steps: 1. i have a datagridview with two columns (LoginName,UserName) 2. the datagridview sorting is set to automatic, so when i click on the column header is sorts well. 3. i put in an event handler for the CellEndEdit Event, so whenever the user of the program changes the content of a cell in the LoginName...
1
7190
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find nothing new or useful contained in this article. Short Review In part one I showed you some...
6
1488
by: gopalsd | last post by:
Hi Friends, Can anyone pls help me to resolve my school test in PERL................ as follows..... #!/usr/bin/perl @data=N; $sum=0; print"enter the required No. of numbers to be inputed : f";
5
4956
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums there are, it crashes. There are currently 6 columns, and I only want 4. How do I remove the last two (discount and date)? Here is a link: http://www.jaredmoore.com/tablesorter/docs/salestable.html Here is some jquery js that I think...
0
10210
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
10039
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
9860
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...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5297
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...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3955
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
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
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.