//只一级排序,按成绩降序排名
#includetypedef struct Stu { char name[30]; int num; float score; }Stu; void quickSort(Stu* p,int low,int high)//按成绩降序, { if(low < high) { int l = low; int h = high; Stu pivot = p[low]; /*让小于中轴在右半边,让大于中轴的在左半边*/ while(l<h) { while(p[h].score <= pivot.score && h>l)//小于中轴 不移,留在原位,往前走直到碰见大于中轴的再移到左边。 { h--; } p[l] = p[h]; while(p[l].score >= pivot.score && l //大于中轴 不移,留在原位,往前走直到碰见小于中轴的再移到右边 { l++; } p[h] = p[l]; } int pos = h;//此时lh相等 p[pos] = pivot; quickSort(p,low,pos-1); quickSort(p,pos+1,high); } } int main(void) { Stu arr[10] = {"zhangsan",1,60, "lisi",2,70, "wangwu",3,20, "liudehua",4,55, "liming",5,80, "guodegang",6,100, "guanyu",7,10, "liubei",8,59, "zhangxueyou",9,99, "xiaoli",10,40}; quickSort(arr,0,9); int i; for(i = 0;i<10;i++) { printf("%s,%d,%.0f\n",arr[i].name,arr[i].num,arr[i].score); } return 0; }
//实现二级排序,先按成绩降序排序,成绩相同再按学号升序排序。
#includetypedef struct _Stu { char name[30]; int num; float score; }Stu; void quickSort(Stu* p,int low,int high)//按成绩降序,成绩如若相等,按学号升序 { if(low < high) { int l = low; int h = high; Stu pivot = p[low]; /*让小于中轴在右半边,让大于中轴的在左半边*/ while(l<h) { while(p[h].score <= pivot.score && h>l) { if(p[h].score < pivot.score)//成绩降序 { h--; } else if(p[h].score == pivot.score && p[h].num > pivot.num)//学号升序,大的留在右边 { h--; } else if((p[h].score == pivot.score && p[h].num < pivot.num))//学号升序,小的跳出循环往左移 { break; } } p[l] = p[h]; while(p[l].score >= pivot.score && l<h) { if(p[l].score > pivot.score)//成绩降序 { l++; } else if(p[l].score == pivot.score && p[l].num < pivot.num)//学号升序 { l++; } else if(p[l].score == pivot.score && p[l].num > pivot.num)//学号升序,小的跳出循环往左移 { break; } } p[h] = p[l]; } int pos = h;//此时lh相等 p[pos] = pivot; quickSort(p,low,pos-1); quickSort(p,pos+1,high); } } int main(void) { Stu arr[10] = {"zhangsan",5,80, "lisi",11,80, "wangwu",3,20, "liudehua",4,55, "liming",1,80, "guodegang",6,100, "guanyu",7,10, "liubei",8,59, "zhangxueyou",9,80, "xiaoli",10,40}; quickSort(arr,0,9); int i; for(i = 0;i<9;i++) { printf("%s,%d,%.0f\n",arr[i].name,arr[i].num,arr[i].score); } return 0; }