快速排序
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; typedef struct sqlist { int *elem; int length; }Sqlist; void q_sort(Sqlist &l,int low,int high) { if (low>=high) { return; } int mid=l.elem[low];//二分指针 int i=low;//底端指针 int j=high;//高端指针 while(i<j){ while(i<j && mid<=l.elem[j])j--;//找到一个小于mid值并位置在mid后面 if (i<j){ l.elem[i]=l.elem[j];//把小的扔到前面去 } while(i<j && mid>l.elem[i])i++;//找到一个大于mid的值并且位置在mid前面 if (i<j){ l.elem[j]=l.elem[i];//把大的扔到前面去 } } l.elem[i]=mid;//最后把其变回来 q_sort(l,low,i-1);//左分块 q_sort(l,i+1,high);//右分块 } int main() { int n; Sqlist a; while(~scanf("%d",&n)) { a.length=(n+1); a.elem=(int *)malloc((a.length+1)*sizeof(int)); for (int i=0; i<n; i++) { scanf("%d",&a.elem[i]); } q_sort(a,0,n-1); for (int i=0;i<n;i++){ printf("%d ",a.elem[i]); } printf("\n"); } return 0; }
#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;typedef struct sqlist{ int *elem; int length;}Sqlist;void q_sort(Sqlist &l,int low,int high){ if (low>=high) { return; } int mid=l.elem[low];//二分指针 int i=low;//底端指针 int j=high;//高端指针 while(i<j){ while(i<j && mid<=l.elem[j])j--;//找到一个小于mid值并位置在mid后面 if (i<j){ l.elem[i]=l.elem[j];//把小的扔到前面去 } while(i<j && mid>l.elem[i])i++;//找到一个大于mid的值并且位置在mid前面 if (i<j){ l.elem[j]=l.elem[i];//把大的扔到前面去 } } l.elem[i]=mid;//最后把其变回来 q_sort(l,low,i-1);//左分块 q_sort(l,i+1,high);//右分块}int main(){ int n; Sqlist a; while(~scanf("%d",&n)) { a.length=(n+1); a.elem=(int *)malloc((a.length+1)*sizeof(int)); for (int i=0; i<n; i++) { scanf("%d",&a.elem[i]); } q_sort(a,0,n-1); for (int i=0;i<n;i++){ printf("%d ",a.elem[i]); } printf("\n"); } return 0;}