常见交换排序有两种:冒泡排序和快速排序
1.冒泡排序
void bubbleSort(int*num,int length)
{
int isSort = 1 ;
int i = 0 ;
int j = 0 ;
for(i;i<length - 1;i++)
{
if(i>0&&isSort ==1)
{
break;
}
printf("the times is %d\n",i);
for(j=0;j<length - i-1;j++)
{
if(num[j] > num[j+1])
{
int tep = num[j+1];
num[j+1] =num [j];
num[j] =tep;
isSort = 0;
}
}
}
}
2.快速排序
快速排序是基于冒泡排序的改进,大体思路就是:先通过交换的方式确定基准轴的位置,即基准轴左侧都不大于基准轴,右侧都不小于基准轴,数组基本有序。其后对左侧和右侧的子序列分别进行递归调用,直到呆排序列只有一个记录,则整个数组排序完成。
代码如下:
int partition(int *num,int left,int right)
{
int low = left;
int high = right;
int key = num[low];
while(low < high)
{
while(num[high] >key&&low<high)
{
high -=1;
}
num[low]=num[high];
while(num[low] < key&&low<high)
{
low+=1;
}
num[high] = num[low];
}
num[low] = key;
return low;
}
void qSort(int*num, int low,int high)
{ if(low < high)
{
int pivotloc = partition(num,low,high);
if(pivotloc < (low + high)/2)
{
qSort(num,1,pivotloc-1);
qSort(num,pivotloc+1,high);
}else{
qSort(num,pivotloc+1,high);
qSort(num,1,pivotloc-1);
}
}
}
void quickSort(int*num,int length)
{
qSort(num,0,length-1);
}