C語言-快速排序

思路

稍後再補

代碼

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>

#define MAX 30

int arr[MAX];

void quickSort(int arr[], int start, int end);
int getIndex(int arr[], int start, int end);
void assertSort(int arr[]);

int main(){
	srand(time(0));
	
	for(int i = 0; i < MAX; ++i){
		arr[i] = rand()%100;
		printf("%d ", arr[i]);
	}
	putchar('\n');
	
	quickSort(arr, 0, MAX-1);

	for(int i = 0; i < MAX; ++i){
		printf("%d ", arr[i]);
	}
	
	putchar('\n');
	assertSort(arr);

	return 0;
}

void quickSort(int arr[], int start, int end){
	if(start < end){
		int index = getIndex(arr, start, end);

		quickSort(arr, start, index-1);
		quickSort(arr, index+1, end);
	}
}
int getIndex(int arr[], int start, int end){
	
	int key = arr[start];

	while(start < end){
		// 在隊尾找到比Key值小的元素,
		while(start < end && key <= arr[end]){
			end--;
		}
		arr[start] = arr[end];
		
		// 在隊頭找到比Key值大的元素
		while(start < end && key >= arr[start]){
			start++;
		}
		arr[end] = arr[start];

	}
	// start 與 end 相等, 
	arr[start] = key;
	return start;

}
void assertSort(int arr[]){
	for(int i = 0; i < MAX-1; ++i){
		assert(arr[i] <= arr[i+1]);
	}
	printf("arr is order!\n");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章