嵌入式:C高级 Day4

嵌入式:C高级 Day4_第1张图片

一、整理思维导图

嵌入式:C高级 Day4_第2张图片

二、写一个函数,获取用户的uid和gid并使用变量接收

嵌入式:C高级 Day4_第3张图片

三、整理冒泡排序、简单选择排序和快速排序的代码 

冒泡排序

嵌入式:C高级 Day4_第4张图片

#include 

void output(int arr[], int len);
void bubble_sort(int arr[], int len);

int main(int argc, const char *argv[])
{
	int arr[] = {9, 6, 15, 11, 23, 14, 32, 12};
	int len = sizeof(arr) / sizeof(arr[0]);
	output(arr, len);
	bubble_sort(arr, len);
	output(arr, len);
	return 0;
}

void bubble_sort(int arr[], int len){
	int count, temp;
	for(int i = 0; i < len; i++){
		count = 0;
		for(int j = 0; j < len - 1 - i; j++){
			if(arr[j] > arr[j + 1]){
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
				count++;
			}
		}
		if(count == 0){
			break;
		}
	}
}

void output(int arr[], int len){
	for(int i = 0; i < len; i++){
		printf("%d ", arr[i]);
	}
	puts("");
}

简单选择排序:

嵌入式:C高级 Day4_第5张图片

#include 

void output(int arr[], int len);
void select_sort(int arr[], int len);

int main(int argc, const char *argv[])
{
	int arr[] = {9, 6, 15, 11, 28, 25, 22, 37, 18};
	int len = sizeof(arr) / sizeof(arr[0]);
	output(arr, len);
	select_sort(arr, len);
	output(arr, len);
	return 0;
}

void select_sort(int arr[], int len){
	int min, temp;
	for(int i = 0; i < len - 1; i++){
		min = i;
		for(int j = i + 1; j < len; j++){
			if(arr[min] > arr[j]){
				min = j;
			}
		}
		if(min != i){
			temp = arr[min];
			arr[min] = arr[i];
			arr[i] = temp;
		}
	}
}

void output(int arr[], int len){
	for(int i = 0; i < len; i++){
		printf("%d ", arr[i]);
	}
	puts("");
}

快速排序:

嵌入式:C高级 Day4_第6张图片

#include 

void output(int arr[], int len);
void quick_sort(int arr[], int low, int high);
int onesort(int arr[], int low, int high);

int main(int argc, const char *argv[])
{
	int arr[] = {9, 6, 13, 11, 19, 25, 12, 37, 22};
	int len = sizeof(arr) / sizeof(arr[0]);
	output(arr, len);
	quick_sort(arr, 0, len - 1);
	output(arr, len);
	return 0;
}

void quick_sort(int arr[], int low, int high){
	while(low >= high){
		return;
	}
	int mid = onesort(arr, low, high);
	quick_sort(arr, 0, mid - 1);
	quick_sort(arr, mid + 1, high);
}

int onesort(int arr[], int low, int high){
	int key = arr[low];
	while(low < high){
		while(low < high && key <= arr[high]){
			high--;
		}
		arr[low] = arr[high];

		while(low < high && key >= arr[low]){
			low++;
		}
		arr[high] = arr[low];
	}
	arr[low] = key;
	return low;
}

void output(int arr[], int len){
	for(int i = 0; i < len; i++){
		printf("%d ", arr[i]);
	}
	puts("");
}

你可能感兴趣的:(c语言,排序算法,算法)