vlambda博客
学习文章列表

默写冒泡排序+直接插入排序

冒泡排序-改进 ,头脑里对这幅图像很清晰,一遍过。

#include<stdio.h>void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;}void bubblesort(int arr[], int length){ int i, j; for (i = 0; i < length; i++) { bool stamp = true; for (j = length - 1; j > i; j--) { if (arr[j] < arr[j - 1]) swap(&arr[j], &arr[j - 1]); stamp = false; } if (stamp == true) { break; } }}
int main(){ int arr[8] = { 5,0,6,9,4,3,1,2 }; int i; bubblesort(arr, 8); for (i = 0; i < 8; i++) printf("%d ", arr[i]); return 0;}

直接插入排序想了一会才想出来,但也是一遍过

#include<stdio.h>void insertionsort(int arr[], int length){ int i, j; for (i = 1; i < length; i++) { if (arr[i - 1] > arr[i]) { int temp = arr[i]; for (j = i - 1; j >= 0 && arr[j] > temp; j--) { arr[j + 1] = arr[j]; } arr[j + 1] = temp; } }}int main(){ int arr[12] = { 5,12,65,45,3,5,15,26,0,18,32,22 }; int i; insertionsort(arr, 12); for (i = 0; i < 12; i++) { printf("%d ", arr[i]); } return 0;}

不错,点赞。