您的位置:首页 > 其它

排序:交换排序(冒泡排序、快速排序)

2013-09-15 04:02 155 查看
交换排序:两两比较待排序元素,发现倒叙交换。

1、冒泡排序

2、快速排序(递归)

#include <stdio.h>
#define NUM 4

/* 冒泡排序 */
void bubbleSort(int* A)
{
for (int i = NUM-1; i >= 1; i--) //控制待排序子序列数,开始NUM-1个,最后2个
{
for (int j = 0; j < i; j++)  //i个数,i-1次排序
{
if (A[j+1] < A[j])
{
int tmp = A[j+1];
A[j+1] = A[j];
A[j] = tmp;
}
}
}
}

/* 快速排序 */
void quickSort(int* A, int low, int high)
{
if (low < high)
{
int tlow = low, thigh = high;
int pos = low;
int tmp = A[pos];
while (tlow <= thigh)
{
while (tmp < A[thigh] && tlow <= thigh) thigh--;
if (tlow <= thigh)
{
A[pos] = A[thigh];
pos = thigh--; //保留空位,thigh置后一次
}
while (A[tlow] < tmp  && tlow <= thigh) tlow++;
if (tlow <= thigh)
{
A[pos] = A[tlow];
pos = tlow++;  //保留空位,tlow前进一次
}
}
A[pos] = tmp;

quickSort(A, low, pos-1);
quickSort(A, pos+1, high);
}
}

int main(void)
{
int a[NUM], i = 0;
printf("Enter %d integers:(ctrl+z to end)\n", NUM);
while ( (scanf("%d", &a[i])) && (i < NUM) ) i++;

quickSort(a, 0, NUM-1);

for (int i = 0; i < NUM; i++)
printf("%d ", a[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: