473,585 Members | 2,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with array

Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped.
I am coping the original array into a temp (iTmp) array to be sorted.
Then, I am using a menu to call each Sort function where I am passing
in iTmp plus the array's
size to be sorted.

-----------------------------------------
while ((iMenuChoice = menu()) != QUIT) // print menu & loop until
QUIT
switch( iMenuChoice ) {
case 1: // user enters 1: selection sort....
selectionSort( iTmpArr, SIZE );
break;
Nov 13 '05 #1
3 2466
ritchie wrote:

Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped. The problem though, is that each time I call the next sort from the
menu (while still in SWITCH statement until QUIT ) the comparisons and
swaps are being incorrectly calculated.

I know this is because the functions are getting the same array.
I am coping the original array into iTmp BEFORE the SWITCH which is
within the while loop.
Is there anywhere else I should be copying the arrays?
I tried to copy the arrays before each function call in the SWITCH but
this didn't work.


Post the whole program.

--
pete
Nov 13 '05 #2


ritchie wrote:
Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped.
I am coping the original array into a temp (iTmp) array to be sorted.
Then, I am using a menu to call each Sort function where I am passing
in iTmp plus the array's
size to be sorted.

-----------------------------------------
while ((iMenuChoice = menu()) != QUIT) // print menu & loop until
QUIT
switch( iMenuChoice ) {
case 1: // user enters 1: selection sort....
selectionSort( iTmpArr, SIZE );
break;
.
.
.
}
}
-----------------------------------------------
Within each sort function I call 'displaySorted' , where I pass in
iTmp(copied array), array size, comparisons & swaps (calculated from
functions).
-------------------------------------
void displaySorted( int iTmpArr[], int iMax, int iComparison, int
iSwaps )
{
int i;

printf("Your Sorted Array:\n");
for(i=0; i<=MAX-1; i++ )
printf("%4d", iTmpArr[i]);
printf("\n");

printf( "Comparison s: %d \n", iComparison );
printf( "Swaps: %d \n", iSwaps );
-----------------------------------------------------+

The problem though, is that each time I call the next sort from the
menu (while still in SWITCH statement until QUIT ) the comparisons and
swaps are being incorrectly calculated.

I know this is because the functions are getting the same array.
I am coping the original array into iTmp BEFORE the SWITCH which is
within the while loop.
I don't believe it would matter, but I would to the array
copying and printing in the while loop.

Is there anywhere else I should be copying the arrays?
I tried to copy the arrays before each function call in the SWITCH but
this didn't work.

Anyone have any ideas?


I assume that when you say it doesn't work that the problem is
incorrect values in the number of comparisons and number of swaps.
If so, you should look carefully at how you define and use these
variables in the sort and/or comparision functions. Here is
an example, untested, of using these variables in a bubblesort and
selectionsort function.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void PointertoOrigin ( int *a, int **pa, size_t);
void bubblesort(void *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps);
void selectionsort(v oid *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps);
void swap(void *e1, void *e2, size_t size);
int cmp(const void *e1, const void *e2);
void PrintArrays(int *a, int **pa,size_t n);
int menuselection(v oid);

int main(void)
{
int array[10] = {4,3,6,1,8,10,2 ,5,7,9};
int *parray[10];
size_t comparisons, swaps;
int choice;
while(1)
{
PointertoOrigin (array,parray,1 0);
choice = menuselection() ;
if(choice == 'q' || choice == 'Q') break;
if(choice < '1' || choice > '2')
{
puts("Invalid entry. Try again");
continue;
}
switch(choice)
{
case '1': bubblesort(parr ay,10, sizeof(*parray) ,
cmp, &comparisons,&s waps);
break;
case '2': selectionsort(p array,10, sizeof(*parray) ,
cmp, &comparisons,&s waps);
break;
}
PrintArrays(arr ay,parray,10);
printf("Number Comparisons: %u\n"
"Number swaps: %u\n\n\n",
comparisons, swaps);
}
return 0;
}
void PointertoOrigin ( int *a, int **pa, size_t n)
{
size_t i;

for(i = 0; i < n;i++)
pa[i] = &a[i];
return;
}

void bubblesort(void *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps)
{
size_t i, sorted = 0;
char *p = (char *) base;

*comparisons = *swaps = 0;
while(!sorted)
{
sorted = 1;
for(i = 0;i < n-1; i++)
{
(*comparisons)+ +; /* increment the comparison variable */
if(cmp(p+(i*siz e),p+((i+1)*siz e))>0)
{
(*swaps)++; /* increment the swap variable */
swap(p+(i*size) ,p+((i+1)*size) ,size);
sorted = 0;
}
}
}
}

void swap(void *e1, void *e2, size_t size)
{
char buf[256], *p1 = (char *)e1, *p2 = (char *)e2;
size_t ms;

for(ms = size; 0< ms; )
{
size_t m = ms < sizeof(buf)?ms: sizeof(buf);
memcpy(buf,p1,m );
memcpy(p1,p2,m) ;
memcpy(p2,buf,m );
ms -= m, p1+=m, p2+=m;
}
return;
}

int cmp(const void *e1, const void *e2)
{
int *i1 = *(int **)e1, *i2 = *(int **)e2;

return (*i1<*i2)?-1:(*i1!=*i2);
}

void PrintArrays( int *a, int **pa, size_t n)
{
size_t i;

printf("The unsorted array: ");
for(i = 0; i < n;i++) printf("%d ",a[i]);
printf("\nThe sorted pointers : ");
for(i = 0; i < n;i++) printf("%d ", *pa[i]);
putchar('\n');
return;
}

void selectionsort(v oid *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps)
{
size_t position, smallest_idx,i;
char *p = (char *)base;

*comparisons = *swaps = 0;
for(position = 0; position < n-1; position++)
{
smallest_idx = position;
for(i = position+1;i < n; i++)
{
(*comparisons)+ +;
if(cmp(p+(i*siz e),p+(smallest_ idx*size)) < 0)
smallest_idx = i;
}
if(smallest_idx != position)
{
(*swaps)++;
swap(p+(smalles t_idx*size),p+( position*size), size);
}
}
}

int menuselection(v oid)
{
char choice[16];

printf("\nSorti ng test\n\t1) BubbleSort\n\t"
"2) SelectionSort\n Enter the number"
"('q' to quit): ");
fflush(stdout);
fgets(choice,si zeof choice, stdin);
return (int)*choice;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #3
buddy!

u need to chek wether the array is sorted correctly or not...if it is
being sorted correctly then the problem lies in the calulation of the
variables..u did not specify wether the actual figure is smaller than
or larger than the calculated figure..if it is smaller then the
problem could be due to initializing of the variables...it may be
adding up previous results...if it is smaller then the loop is not set
right for calculation...c hek it closely...it depends a lot on where
exactly u are incrementing the comparision and swap variables..
hope it helps...
do let me know if any more input is required..
u can send in the omplete code to hp*****@vcustom er.net
if u want me to take a look at it
Nov 13 '05 #4

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

Similar topics

4
3827
by: JesusFreak | last post by:
From: us_traveller@yahoo.com (JesusFreak) Newsgroups: microsoft.public.scripting.jscript Subject: toolbar script problem NNTP-Posting-Host: 192.92.126.136 Recently, I downloaded the following beautiful script "http://javascript.internet.com/navigation/toolbar-menu.html". It works like a charm. I made my webpage in frames, where the...
0
285
by: crawlerxp | last post by:
This is the problem: I do not get the output I need when encoding and decoding data using rijndael alghoritm. Look at the code and see what the problem is actually: Please paste this code into your Visual Studio and compile it + run it; so you can see what the actual problem is. Thanks. code:
8
15351
by: Brady | last post by:
Hi, I'm having a problem reading and writing to a file. What I'm trying to do is read a file, modify the portion of the file that I just read, and then write the modified data back to the same location in the file. What is happening, is I can read the file, either in entirety or only part of it. And no matter what I try setting the...
8
3357
by: mytfein | last post by:
Hi Everyone, Background: Another department intends to ftp a .txt file from the mainframe, for me to process. The objective is to write a vb script that would be scheduled to run daily to process this .txt file. Goal: I am working on a vba script to:
8
10705
by: intrepid_dw | last post by:
Hello, all. I've created a C# dll that contains, among other things, two functions dealing with byte arrays. The first is a function that returns a byte array, and the other is intended to receive a byte array as one of its parameters. The project is marked for COM interop, and that all proceeds normally. When I reference the type...
4
11218
by: daroman | last post by:
Hi Guys, i've problem with my small C++ programm. I've just small template class which represetns a array, everything works fine up to combination with std::string. I did tried it with M$ VC++ and with GCC (Cygwin and Linux) and my problem is when i try do this int main(int argc, char **argv) { array<std::stringa(10); a = "Huhuhu"; <---...
5
2552
by: weidongtom | last post by:
Hi, I tried to implement the Universal Machine as described in http://www.boundvariable.org/task.shtml, and I managed to get one implemented (After looking at what other's have done.) But when I use to run a UM program, I kept on getting error messages. I have used someone else's implementation and it runs fine. I have compared my code...
9
2494
by: weidongtom | last post by:
Hi, I've written the code that follows, and I use the function add_word(), it seems to work fine *before* increase_arrays() is called that uses realloc() to allocate more memory to words. But *after* calling increase_arrays(), I received segmentation fault. I tried to step it through gdb, and I found out that after calling...
3
6342
by: raylopez99 | last post by:
Below is my problem. I've narrowed it down to one thing: my unfamiliarity on how class instances are instantiated in an array. This is because the "un-array" / "non-array" version of the program works fine (see below). So what is the problem? I get a null reference on the line below at *!&!* "Unhandled Exception:...
25
2339
by: biplab | last post by:
Hi all, I am using TC 3.0..there if I declare a integer array with dimension 162*219...an error msg saying that too long array is shown....what should I do to recover from this problem???
0
7900
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...
0
8192
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. ...
0
8332
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...
0
8204
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...
1
5705
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...
0
5382
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...
0
3853
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1442
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1167
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...

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.