Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created September 20, 2016 14:27
Show Gist options
  • Save limboinf/20a870e4034bc6b9d494e9c99f25d064 to your computer and use it in GitHub Desktop.
Save limboinf/20a870e4034bc6b9d494e9c99f25d064 to your computer and use it in GitHub Desktop.
快速排序
#include <stdio.h>
int a[101], n;
void quicksort(int left, int right)
{
int i, j, t, temp;
if (left > right)
return;
temp = a[left]; //基准数
i = left;
j = right;
while (i != j)
{
//先从右边开始找
while (a[j] >= temp && i < j)
j--;
//再从左边开始找
while (a[i] <= temp && i < j)
i++;
//两边都找到符合条件的则停下来,交换数据
if (i < j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
//数据交换完毕后再次继续找, 直到i=j碰头
}
//最终将基数位归位, 也就是将基准数与最终碰头的位交换数据
a[left] = a[i];
a[i] = temp;
// 上面是一趟交换并将基准数归位的过程
// 下面需要递归处理被分隔的左右两列
// 因为最终在i处停了下来, 被分隔2列, i左边的都小于i,i右边的都大于i
quicksort(left, i-1); //继续处理左边的
quicksort(i+1, right); //继续处理右边的
}
int main()
{
int i, j, t;
scanf("%d", &n);
for (i=0; i< n; i++) {
scanf("%d", &a[i]);
}
quicksort(0, n-1);
for (i = 0; i < n; i++) {
printf("%d, ", a[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment