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

交換排序(氣泡排序,快速排序)

/*
交換排序:氣泡排序,快速排序
執行環境:VS2010
*/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define OK 1
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50

typedef struct
{
	int value;
}RedType;

typedef struct
{
	RedType red[MAXSIZE+1];	//red[0]用作哨兵單元
	int length;
}SqList;

SqList *CreateSqList()
{
	int i = 0;
	int j = 0;
	char buf[4*MAXSIZE] = "";
	char *ptr = NULL;
	SqList *sqlist = (SqList *)malloc(sizeof(SqList));
	memset(sqlist, 0, sizeof(SqList));

	printf("請輸入待排序資料,以逗號分隔,以分號結束\n"
		"例:23,12,65,36,35;\n"
		"input:");
	scanf("%s", buf);

	ptr = buf;
	sqlist->red[i].value = 0;	//red[0]不存值用作哨兵單元
	i = 1;
	while(*ptr != ';')
	{
		sqlist->red[i].value = atoi(ptr);
		i++;

		ptr = strstr(ptr, ",");
		if(!ptr)
		{
			break;
		}
		ptr++;
	}
	sqlist->length = (i - 1);

	return sqlist;
}

//氣泡排序
int BubbleSort(SqList *sqlist)
{
	int i = 0;
	int j = 0;
	int change = TRUE;

	for(i = 1;  (change == TRUE)&&(i <= sqlist->length); i++)
	{
		change = FALSE;	
		for(j = 1; j <= sqlist->length - i + 1; j++)
		{
			if(sqlist->red[j].value < sqlist->red[j-1].value)
			{
				sqlist->red[0] = sqlist->red[j];
				sqlist->red[j] = sqlist->red[j-1];
				sqlist->red[j-1] = sqlist->red[0];
				change = TRUE;
			}
		}
	}

	return OK;
}

//快速排序的一趟交換過程
int Partition(SqList *sqlist, int low, int high)
{
	int pivotkey = 0;
	sqlist->red[0] = sqlist->red[low];	//順序表的第一個記錄做樞軸記錄
	pivotkey = sqlist->red[low].value;	//樞軸記錄關鍵字

	while(low < high)		//從表的兩端向中間掃描
	{
		while((low < high) && (pivotkey <= sqlist->red[high].value))
		{
			high--;
		}
		sqlist->red[low] = sqlist->red[high];	//將比樞軸記錄小的記錄移到低端
		while((low < high) && (pivotkey >= sqlist->red[low].value))
		{
			low++;
		}
		sqlist->red[high] = sqlist->red[low];	//將比樞軸記錄大的記錄移到高階
	}

	sqlist->red[low] = sqlist->red[0];	//樞軸記錄到位
	return low;	//返回樞軸的位置
}

//對順序表的子表sqlist->red[low...high]做快速排序
int QSort(SqList *sqlist, int low, int high)
{
	int pivotloc = 0;
	if(low < high)	//這個是結束條件
	{
		pivotloc = Partition(sqlist, low, high);	//將sqlist->red[low...high]一分為二
		QSort(sqlist, low, pivotloc - 1);	//對高子表排序
		QSort(sqlist, pivotloc + 1, high);	//對低子表排序
	}
	return OK;
}

//快速排序
int QickSort(SqList *sqlist)
{
	QSort(sqlist, 1, sqlist->length);

	return OK;
}

//打印表中資料
int PrintSqList(SqList sqlist)
{
	int i = 0;
	for(i = 1; i <= sqlist.length; i++)
	{
		printf("%d,", sqlist.red[i].value);
	}
	printf("\b;\n");
	return OK;
}

int main()
{
	SqList *sqlist = NULL;
	SqList *testSqList = NULL;
	sqlist = CreateSqList();
	testSqList = (SqList *)malloc(sizeof(SqList));

	printf("\n氣泡排序:\n");
	memcpy(testSqList, sqlist, sizeof(SqList));
	PrintSqList(*testSqList);
	BubbleSort(testSqList);
	PrintSqList(*testSqList);

	printf("\n快速排序:\n");
	memcpy(testSqList, sqlist, sizeof(SqList));
	PrintSqList(*testSqList);
	QickSort(testSqList);
	PrintSqList(*testSqList);

	free(testSqList);
	free(sqlist);
	system("pause");
	return 0;
}