C语言下使用快速排序qsort

来源:互联网 发布:矩阵分析引论详细答案 编辑:程序博客网 时间:2024/05/01 03:30

 /**
 *to read the data from the file ,and call the quick-sort methods to sort the data
 */

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
       int x;
       int y;
}Node;
      

int comp(const void *, const void *);

int main(int argc, char *argv[])
{
    int n,
        //*a,
        i,j,k;
    struct node * a;
       
    FILE *file;
    if((file =fopen("data","r"))==NULL ){
        printf("can not open file./n");
        exit(0);        
    }
    fscanf(file,"%d",&n);
    if(n < 0){
         printf("no number./n");   
         exit(0);
    }
   
    //a = (int *)malloc(n * sizeof(int));
    a = (struct node *)malloc(n * sizeof(struct node));
     
    //fread(a,sizeof(int),n,file); this method is used to reand the binary file
    for(i= 0 ; i < n; i++)
        fscanf(file,"%d %d",&a[i].x,&a[i].y);
 
    qsort(a,n,sizeof(Node),comp);
   
    for(i = 0 ;i < n; i++)
          printf("%3d%3d/n",a[i].x,a[i].y);
         
    printf("/n"); 
 

 fclose(file); 


  system("PAUSE"); 
  return 0;
}

 

/*to sort the node by x ascendingly, if the x of both two nodes equals,than compare the y*/
int comp(const void *a, const void *b){
    Node *aa = (Node *)a;
    Node *bb = (Node *)b;
    if(aa->x > bb ->x)
             return 1;
    else if(aa->x == bb->x)
         return (aa->y - bb->y);
    else
        return -1;
    //return (*(int *)a - *(int *)b); //to compare the int type ,and you can imply on
}