473,908 Members | 4,944 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 2484
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
3860
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 nav-frame shows the menubar, so whenever I click a link in the menubar, it opens in the frame below. But...
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
15366
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 position to, using fsetpos, it always gets set back to the very beginning of the file. I
8
3379
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
10732
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 library in the VB6 project, and write the code to call the function that returns the byte array, it works
4
11244
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"; <--- with gcc i got a crash !
5
2568
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 with other's and I still can't figure it out what's wrong with mine. So please help me out, after 3...
9
2525
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 increase_arrays(), words's original value is modified, and if I tried to access it, I get <address 0x11 out of...
3
6362
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: System.NullReferenceException: Object reference not set to an instance of an object.? RL
25
2371
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
10031
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
10913
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
11042
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
9721
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
7246
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
6134
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4770
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
4336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3355
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.