1. 程式人生 > >排序:交換排序(氣泡排序、快速排序)

排序:交換排序(氣泡排序、快速排序)

交換排序:兩兩比較待排序元素,發現倒敘交換。

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;
}