473,769 Members | 5,131 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
Simon Bachmann writes:
ruel loehr wrote:

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!


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.

Hope you understand my description. it isn't that clear...


It's very clear. And kind of clever, too.
Nov 14 '05 #11
CBFalconer <cb********@yah oo.com> writes:
I sent you an e-mail a few days ago, and got no reply, yet
something in the newsgroups got an immediate response. Did you
receive anything from me? I have some things to bring up.


Somehow Spamassassin decided it was spam. Will send reply.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #12
Ben Pfaff wrote:
CBFalconer <cb********@yah oo.com> writes:
I sent you an e-mail a few days ago, and got no reply, yet
something in the newsgroups got an immediate response. Did you
receive anything from me? I have some things to bring up.


Somehow Spamassassin decided it was spam. Will send reply.


It would have the same From and Reply to as this, if that triggers
things.

--
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 #13
On 17 Jan 2004 08:28:31 -0800, ru*******@hotma il.com (ruel loehr)
wrote:
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:


If you attack the problem from the back end, it may be easier. A
merge would normally have two inputs and an output. If you consider
the last entry of A as input 1, the last used entry of B as input 2,
and the last entry of B as the output, you can safely move data from
the appropriate either input to output repeatedly until you have
finished with the first elements of both inputs.
<<Remove the del for email>>
Nov 14 '05 #14
Tom St Denis wrote:

[...] My guess was that was intentional [e.g. give horribly bad advice so the
stupid fucking idiot won't fucking come back here to cheat on his/her/it's
assignment].


Yeah!

You really are a mean, bad, and way-cool dude, talking like that.

Rrrespect,

Sidney

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

ru*******@hotma il.com (ruel loehr) wrote in message news:<50******* *************** ****@posting.go ogle.com>...
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 #16
Barry Schwarz wrote:

On 17 Jan 2004 08:28:31 -0800, ru*******@hotma il.com (ruel loehr)
wrote:
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:


If you attack the problem from the back end, it may be easier. A
merge would normally have two inputs and an output. If you consider
the last entry of A as input 1, the last used entry of B as input 2,
and the last entry of B as the output, you can safely move data from
the appropriate either input to output repeatedly until you have
finished with the first elements of both inputs.


I think that's the solution that the author of the problem had in mind.

--
pete
Nov 14 '05 #17
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.

--
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 #18
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.


You still need another object to keep track of
the last (empty) element of b.

If you copy a[0], then you're done.
If you copy b[0], then you can copy the rest of a[]
without comparisons between the rest of the elements.

--
pete
Nov 14 '05 #19
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.

From practical point of view,
the function can be written as a template.

You can change E_TYPE to any arithmetic type without
affecting the ouptut of merge.c
If you wanted to sort non arithmetic types,
then the GT() macro would also need to be rewritten,
but you have to write a new compar function everytime you
want use qsort in a new way, so it's no big deal.

/* BEGIN merge.c */

#include <stdio.h>

#define arrayA {4, 7, 10, 15, 17}
#define arrayB {2, 4, 14, 27, 'X', 'X', 'X', 'X', 'X'}
#define E_TYPE int
#define GT(A, B) (*(A) > *(B))
#define N(E) (sizeof (E) / sizeof *(E))

typedef E_TYPE e_type;

void Merge(e_type *, size_t, e_type *, size_t);

int main(void)
{
e_type a[] = arrayA;
e_type b[] = arrayB;
size_t element;

Merge(a, N(a), b, N(b));
for (element = 0; element != N(b); ++element) {
printf("%lu, ", (long unsigned)b[element]);
}
putchar('\n');
return 0;
}

void Merge(e_type *a, size_t na, e_type *b, size_t nb)
{
e_type *end;

end = b + nb--;
nb -= na--;
for (;;) {
if (GT(b + nb, a + na)) {
*--end = b[nb];
if (nb == 0) {
break;
} else {
--nb;
}
} else {
*--end = a[na];
if (na == 0) {
return;
} else {
--na;
}
}
}
do {
*--end = a[na];
} while (na-- != 0);
}

/* END merge.c */

I like pointers:
/*
void Merge(e_type *a, size_t na, e_type *b, size_t nb)
{
e_type *end, *B, *A;

end = b + nb;
A = a + na - 1;
B = b + nb - na - 1;
for (;;) {
if (GT(B, A)) {
*--end = *B;
if (B == b) {
break;
} else {
--B;
}
} else {
*--end = *A;
if (A == a) {
return;
} else {
--A;
}
}
}
*--end = *A;
while (A != a) {
*--end = *--A;
}
}
*/
--
pete
Nov 14 '05 #20

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
9583
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
9423
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
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...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
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...
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?
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.