快速排序(C实现)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序(C实现)相关的知识,希望对你有一定的参考价值。
1 // 2 // main.c 3 // QSort 4 // 5 // Created by 何进明 on 16/3/22. 6 // Copyright © 2016年 bbcai. All rights reserved. 7 // 8 9 #include<stdio.h> 10 #include<stdlib.h> 11 typedef struct Node{ 12 int x; 13 struct Node *next; 14 }Node,*List; 15 void CreateList(int num,List *list){ 16 int i = 0; 17 List headNode = *list; 18 List p,r; 19 r = headNode; // r指向链表的结尾 20 for(i = 0;i<num;i++) 21 { 22 p = (Node *)malloc(sizeof(Node)); 23 scanf("%d",&(p->x)); 24 // printf("you has been input the %d number:%d\n",i + 1,p->x); 25 r->next = p; 26 r = p; //r总是指向当前尾结点 27 } 28 r->next = NULL; 29 *list = (*list)->next; 30 // headNode = headNode->next; /*headNode同样是一个指向头节点指针的局部指针,不能操纵头节点的指针,但是可以操纵头节点指针指向的结构体*/ 31 } 32 33 int NumberInList(List list,int n){ 34 int i = 1; 35 if(n == 1) 36 { 37 return list->x; 38 } 39 while(i < n && list !=NULL){ 40 list = list->next; 41 i ++; 42 } 43 return list->x; 44 45 } 46 void Swap(List *list,int a,int b) 47 { 48 printf("开始交换数据\n"); 49 List L = *list; 50 int tmp1 = 0; 51 int tmp2 = 0; 52 int i = 1; 53 tmp2 = NumberInList(L,b); 54 while( i < a){ //定位a的结点 55 i++; 56 L = L->next; 57 } 58 tmp1 = L->x; 59 L->x = tmp2; 60 while( i < b) 61 { 62 i++; 63 L = L->next; 64 } 65 L->x = tmp1; 66 } 67 int Partition(List *list,int low, int high) 68 { 69 printf("开始分区\n"); 70 List L = *list; 71 int mark = low; //假设以第一个为标记 72 // int mark = L->x; /*这个不行*/ 73 int Markx = NumberInList(L,mark); 74 while(low < high) /*从表的两端交替向中间扫描*/ 75 { 76 while(low < high && NumberInList(L,high) >= Markx) /*缺等号会一直不停交换数据,下面一样*/ 77 high --; 78 Swap(list,low,high); 79 while(low < high && NumberInList(L,low) <= Markx) 80 low++; 81 Swap(list,low,high); 82 } 83 return low; 84 } 85 void QSort(List *list,int low,int high) 86 { 87 printf("开始快排\n"); 88 int mark ; 89 if(low < high) 90 { 91 mark = Partition(list,low,high); 92 QSort(list,low,mark-1); 93 QSort(list,mark+1,high); 94 } 95 } 96 int main(int argc, const char * argv[]) 97 { 98 int num; 99 List list; 100 list =(Node *)malloc(sizeof(Node)); 101 num = 0; 102 scanf("%d",&num); 103 printf("you has been input the total number\n"); 104 CreateList(num,&list); 105 QSort(&list,1,num); 106 while (list!=NULL) { 107 printf("%d ",list->x); 108 list = list -> next; 109 } 110 printf("\n that‘s all,thx "); 111 return 0; 112 }
以上是关于快速排序(C实现)的主要内容,如果未能解决你的问题,请参考以下文章