Skip to content

Instantly share code, notes, and snippets.

@JulesWang
Created May 6, 2011 06:18
Show Gist options
  • Save JulesWang/958514 to your computer and use it in GitHub Desktop.
Save JulesWang/958514 to your computer and use it in GitHub Desktop.
quick sort 快速排序
#include <stdio.h>
void qsort(int *array, int left, int right);
int main()
{
int array[] = {8,2,6,12,1,9,5};
int i = 0;
qsort(array, 0, 6);
for(i=0; i<7; i++)
printf("%d\t",array[i]);
getch();
return 0;
}
void qsort(int *array, int left, int right)
{
int i = left;
int j = right;
int pivot = 0;
if(left >= right)
return;
//pivot 去第一个数为支点
pivot = array[left];
while(i < j)
{
//从右往左找
while(i < j && array[j] > pivot)
j--;
//找到后,填补空的,i坐标后移
if(i < j)
array[i++] = array[j];
//从左往右找
while(i < j && array[i] < pivot)
i++;
//找到后,填补空的,j坐标前移
if(i < j)
array[j--] = array[i];
}
//支点放到“支点”的位置,此数字的位置已定
array[i] = pivot;
qsort(array, left, i-1);
qsort(array, i+1, right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment