swap for bubble sort with structs
Nov 20, 2010 at 3:20pm UTC
My teacher told me to use pointers in the swap function like
t = *i;
*i = *j;
*j = t;
but i have no idea how to do it with array of structs
Here's my code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <stdio.h>
#include <stdlib.h>
struct example
{
double num1;
int num2;
};
void swap(struct example* i, struct example* j)
{
double t;
t = i->num1;
i->num1 = j->num1;
j->num1 = t;
int s;
s = i->num2;
i->num2 = j->num2;
j->num2 = s;
return ;
}
void sort(struct example* mass, int n)
{
for (int i = 1; i <= n; i++)
{
bool swapped;
swapped = false ;
for (int j = i; j < n-1; j++)
{
if (mass[j].num2 > mass[j+1].num2)
{
swap(&mass[j],&mass[j+1]);
swapped = true ;
}
if (mass[j].num2 == mass[j+1].num2)
{
if (mass[j].num1 > mass[j+1].num1)
{
swap(&mass[j],&mass[j+1]);
swapped = true ;
}
}
}
if (!swapped)
{
break ;
}
}
printf("After\n" );
for (int j = 0; j < n; ++j)
{
printf("%f %d\n" , (mass[j].num1), (mass[j].num2));
}
}
int main()
{
int n;
scanf("%d" , n);
struct example* mass = new struct example[n];
for (int i = 0; i < n; ++i)
{
scanf("%f %d" , &(mass[i].num1), &(mass[i].num2));
}
printf("Before\n" );
for (int i = 0; i < n; ++i)
{
printf("%f %d\n" , (mass[i].num1), (mass[i].num2));
}
sort(mass,n);
return 0;
}
Nov 20, 2010 at 4:13pm UTC
Your teacher gave you the solution:
1 2 3 4 5 6 7 8
void swap(struct example* i, struct example* j)
{
example t;
t = *i;
*i = *j;
*j = t;
}
Also, line 57 must be
scanf("%d" ,& n);
and I think line 6 must be
float num1;
because scanf on line 61 expect a float.
EDIT: your sorting algorithm doesn't work as expected, here's the fixed version:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
void sort(struct example* mass, int n)
{
int i=0;
bool swapped=true ;
while (swapped) // loop until no more values were swapped
{
i++;
swapped = false ;
for (int j = 0; j < n-i ; j++)
{
if (mass[j].num2 > mass[j+1].num2)
{
swap(&mass[j],&mass[j+1]);
swapped = true ;
}
if (mass[j].num2 == mass[j+1].num2)
{
if (mass[j].num1 > mass[j+1].num1)
{
swap(&mass[j],&mass[j+1]);
swapped = true ;
}
}
}
}
printf("After\n" );
for (int j = 0; j < n; ++j)
{
printf("%f %d\n" , (mass[j].num1), (mass[j].num2));
}
}
http://www.algolist.net/Algorithms/Sorting/Bubble_sort
Last edited on Nov 20, 2010 at 4:50pm UTC
Nov 20, 2010 at 6:58pm UTC
Thanks a lot!
Topic archived. No new replies allowed.