Sorting Techniques (Non-recursive):
Sorting techniques considered here are internal sorting techniques. The data to be sorted is in memory usually in an array. It could be an array of integers, characters, strings or of the defined structure type. To test a sorting algorithm we require large data set. Data is generated using random (rand()) function. The array of random integers in the range 0 to 99 is generated by using following code:
void generate ( int * a, int n)
{
int i;
for (i=0; i<n; i++) a[i]=rand()%100;
}
In reality, data to be sorted is externally stored in files. One needs to read data from files and bring it into memory in an array before sorting and sorted array also need to be written back to an external file.
Suppose the records to be sorted containing the name, age and salary of a set of employees are in a text file “employee.txt” as follows:
Rajiv 43 100000
Prakash 34 29000
Vinay 35 20000
..................................
The data is read into memory in an array of structures as follows :
1. Variable declarations & main program:
typedef struct
{
char name[30];
int age;
int salary;
}
RECORD;
RECORD emp[100];
main()
{
int n;
n=readFile(emp);
sort(emp,n);
writeFile(emp,n);
}
2. Function for reading from a file:
int readFile(RECORD *a)
{
int i=0;
FILE *fp;
if((fp=fopen("emp.txt","r"))!=NULL)
while(! feof(fp))
{
fscanf(fp,"%s%d%d", a[i].name,
&a[i].age, &a[i].salary);
i++;
}
return i-1; // number of records
read
}
3. Function for writing to a file:
void writeFile(RECORD *a, int n)
{
int i=0;
FILE *fp;
if((fp=fopen("sortedemp.txt","w"))!=NULL)
for(i=0;i<n; i++)
fprintf(fp,"%s\t%d\t%d\n", a[i].name,
a[i].age, a[i].salary);
}
Thanks
Mukesh Rajput
Post A Comment:
0 comments: