-
home streak
After quite alot of babbling and working my code is almost done...
What i would love to know if how can I make the quicksort work for all 3 of my requested sort types a,b,c (D+E are something different) thanks again for your input :-P
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct surv_list SLIST;
struct surv_list {
int id;
int wage;
int sex;
int age;
};
int sort_id(const void *v1, const void *v2) {
SLIST *a1=(SLIST *)v1;
SLIST *a2=(SLIST *)v2;
return (a1->id - a2->id);
}
int main()
{
int /* PersonID,Wage,Sex,Age, */ n, i;
SLIST a[10], *aptr=a;
printf("please enter the amount of people you will use \n");
scanf("%d",&n);
printf("\n=%d\n\n", n);
for (i=0; i<n; i++)
{
printf("please enter the Person ID (person %d)\n", n);
scanf("%d",&a[i].id);
printf("please enter the Wage (person %d)\n", n);
scanf("%d",&a[i].wage);
printf("please enter the Age (person %d)\n", n);
scanf("%d",&a[i].age);
printf("please enter the Sex use 1 for male and 0 for female (person %d)\n", n);
scanf("%d",&a[i].sex);
}
printf("\t Survey Data:\n");
printf("\t~~~~~~~~~~~~~~~~~~~\n");
for (i=0; i<n; i++)
{
printf("Person %d\t", i);
printf("ID: %d\t", a[i].id);
printf("Wage: %d\t", a[i].wage);
printf("Sex: %d\t", a[i].sex);
printf("Age: %d\t\n", a[i].age);
}
int t;
char sort;
t=1;
while (t==1)
{
printf("\n\rHow do you want the data to be sorted ?");
printf("\n\rAscending by Person ID,type a");
printf("\n\rAscending by Wage, type b");
printf("\n\rAscending by Age, type c");
printf("\n\rOnly females, print d");
printf("\n\rOnly males, print e\n\r");
scanf("\n%c",&sort);
switch(sort) {
case 'a':
case 'A':
qsort(a, n, sizeof(SLIST), sort_id);
}
printf("\t Survey Data:\n");
printf("\t~~~~~~~~~~~~~~~~~~~\n");
for (i=0; i<n; i++)
{
printf("Person %d\t", i);
printf("ID: %d\t", a[i].id);
printf("Wage: %d\t", a[i].wage);
printf("Sex: %d\t", a[i].sex);
printf("Age: %d\t\n", a[i].age);
}
printf("Would you like to sort the data again Yes = 1 No = 0 \n");
scanf("%d",&t);
}return 0;
}
-
I suppose simplest would be to write new functions, sort_Wage, and sort_Age, which do the same thing as sort_id, except instead of using the ->id part of the struct, they use ->wage and ->age
-
Just a quick little thing, when you collect the input, you should use the variable 'i' instead of 'n' in:
Code:
for (i=0; i<n; i++)
{
printf("please enter the Person ID (person %d)\n", n);
scanf("%d",&a[i].id);
printf("please enter the Wage (person %d)\n", n);
scanf("%d",&a[i].wage);
printf("please enter the Age (person %d)\n", n);
scanf("%d",&a[i].age);
printf("please enter the Sex use 1 for male and 0 for female (person %d)\n", n);
scanf("%d",&a[i].sex);
}